VOID function

What is wrong with the following function?

void Square (int& x)
{
x = x * x;
return 0;
}
It's a void function so...(fill in the blank).
The first line says something completely different to what the function/method actually does ;-) Does that help?
return 0;
*argues that it's wrong because it returns void and takes the value by reference instead of taking the parameter by value and returning an int*
When you have a void-function you must use return;

So change it to
1
2
3
4
5
void Square (int& x)
{
    x = x * x;
    return;
}


or as Disch recomments:
1
2
3
4
int Square (int x)
{
    return (x * x);
}

I would use the second one, but that depends on how you want to use the function.
Well, the problem was return 0;, like blackcoder41 said.
When you have a void-function you must use return;


Why? I was under the impression that if the method returned void i.e. nothing, then you didn't use return ?

Beginner here :)
return; is optional in void functions.
You can use a return without a value to return from the function early, e.g. in a loop. It's a top method for making non-sensical code.
I'm confused!! So you're saying that if I change it to read return; instead of return 0; this program will work? I know that return 0; is a 'main' function that returns a function value and I know that the VOID function does not. Is this why?? I thought that both could be alternated.
return does 2 things:

1) it exits the function
2) it gives back the return type to the calling function.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
int AFunction()  //  the 'int' specifies the return type
{
  return 5;  // the function returns 5
}

int main()
{
  int myvar;
  myvar = AFunction();  // the return value gets assigned to myvar
    // since AFunction returned 5, this means myvar == 5

  return 0;
}


What you return depends on the return type of the function. Here, 'AFunction' returns an int, therefore you need to return an int from it.

void functions don't return anything, so if you try to return an int, that doesn't make any sense because an int isn't a void.
Thanks for the explanation Disch / chrisname.
what i meant was you have to use return; instead of return whatever;, when you use return in a void function :-)
i always keep the optional return; so my code is consistent.

but doesnt matter what i meant, as long as you understood disch's and chrisname's explanations :D
Topic archived. No new replies allowed.