VOID function

Mar 14, 2010 at 2:25am
What is wrong with the following function?

void Square (int& x)
{
x = x * x;
return 0;
}
Mar 14, 2010 at 2:55am
It's a void function so...(fill in the blank).
Mar 14, 2010 at 7:10am
The first line says something completely different to what the function/method actually does ;-) Does that help?
Mar 14, 2010 at 7:50am
return 0;
Mar 14, 2010 at 8:01am
*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*
Mar 14, 2010 at 7:00pm
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.
Mar 15, 2010 at 1:09am
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 :)
Mar 15, 2010 at 1:14am
return; is optional in void functions.
Mar 15, 2010 at 1:30am
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.
Mar 15, 2010 at 1:47am
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.
Mar 15, 2010 at 1:53am
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.
Mar 15, 2010 at 1:57am
Thanks for the explanation Disch / chrisname.
Mar 15, 2010 at 5:53pm
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.