void return statement

closed account (4ET0pfjN)
is this good programming practice to use return as such:

1
2
3
4
5
6
7
8
9
10
void foobar(int n)
{
   if ( n > 99 )
   {
      cout << "What's up, you?" << endl;
      return;
   }
	
   cout << "Go home" << endl;
}


1
2
3
4
int main()
{
 foobar(99);//NB: "Go home" not outputted
}
Last edited on
void functions aren't value returning. Therefore, does not need "return;" and "go home" would be outputted even if n was < 99. try an if-else statement
Last edited on
void functions aren't value returning. Therefore, does not need "return;" and "go home" would be outputted even if n was < 99. try an if-else statement


I'm pretty sure you're wrong.

As for the actual question, I doubt it because it could be easily missed.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int yourAnIdiot()
{
  int guessWhat = 69;

  return GuessWhat;
} // yourAnIdiot value returning function that requires a return statement

int main()
{
  int lol;
  lol = yourAnIdiot();

  if (lol == 69)
  {
    cout << "You're an idiot" << endl;
  }

  return 0;
}
@ohmymosh: What are you trying to prove? No, a void function doesn't require a return statement. Yes, you may provide it with one or more anywhere in the code, which will cause the function to return at that point. No, you may not return an actual value, it will just cause the function to return before reaching the end.
@BlackSheep so I wasn't wrong.
Last edited on
I should probably clarify. A void returning function doesn't need a return statement. But having one causes the expected results:

1
2
3
4
void foo() {
    return;
    std::cout<<"Test"; //this is never printed
}
This is valid code
1
2
3
4
5
6
7
8
9
10
void foobar(int n)
{
   if ( n > 99 )
   {
      cout << "What's up, you?" << endl;
      return;
   }
	
   cout << "Go home" << endl;
}


but it is unreadable. Try to write simple clear code that is easy to read. You could to write the function without intermediate return statement

1
2
3
4
5
6
7
8
9
10
11
void foobar(int n)
{
   if ( n > 99 )
   {
      cout << "What's up, you?" << endl;
   }
   else
   {	
      cout << "Go home" << endl;
   }
}
Last edited on
Topic archived. No new replies allowed.