function without a return statement

I have found the following code in a book
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

class User {
     string name;
     int age;
public:
     User( string str, int yy ) { name = str; age = yy; }
     friend ostream& operator<<(ostream& os, const User& user) {     //(C)
          os << "Name: " << user.name << " Age: " << user.age << endl;
     }
};

int main()
{
     User us( "Zaphod", 119 );
     cout << us << endl;         // Name: Zaphod Age: 119            //(D)
     return 0;
}

The operator << is overloaded but the return os; statement is missing. I thought this was an error but g++ compile this source and I can run it without errors in linux. How can cout << us return a reference to cout if the overloaded operator does not have the return statement?
I think that the GCC allows that kind of thing... (returning the value of the last expression) but line eleven should read
11 return os << "Name: " << user.name << " Age: " << user.age << endl;

You can force the error by asking g++ to be strictly conformant to a specific standard.

g++ -Wall -pedantic -std=c++98 ...

or, IIRC,

g++ -Wall -pedantic -ansi ...

for the current standard (which is currently C++98).

Hope this helps.
Last edited on
Thanks for your answer, the options you suggest for g++ gives only warnings not errors. It seems that the standard allows that the return statement is missing from a function but the resulting behavior is undefined.

I guessed too that gcc returns the the value of last expression but if you try the following code you don't get the sum result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

class User {
     string name;
     int age;
public:
     User( string str, int yy ) { name = str; age = yy; }
     friend ostream& operator<<(ostream& os, const User& user) {     //(C)
          os << "Name: " << user.name << " Age: " << user.age << endl;
     }
	int sum(int a, int b) {
		a + b;
	}
};

int main()
{
     User us( "Zaphod", 119 );
     cout << us << endl;         // Name: Zaphod Age: 119            //(D)
	 cout << us.sum(4, 5) << endl; 
     return 0;
}


what I'm really interested in is how gcc behaves in such situations.
I don't think there is a specified behavior, but I'm not going to read through the GCC docs right now...

If you want errors, use --pedantic-error.

Hope this helps.
Topic archived. No new replies allowed.