Reputation: 147
Why and how does this code work?
#include <iostream>
using namespace std;
void nothing()
{
false;
}
int main()
{
cout << "Working" << endl;
nothing();
cout << "It worked!" << endl;
}
As you can see, the function definition of the function nothing()
has nothing but a statement false;
in it, but still it compiles and runs fine, doing nothing. How and why is this possible? Am I missing something here?
Upvotes: 0
Views: 95
Reputation: 206737
false;
is a valid statement in C++. It doesn't do anything useful but it is still valid. Most compilers will probably remove that line from the object code they create for the function.
Some compilers, with the right compiler flags, will let you know that the statement has no effect. With g++ --Wall
, I get:
socc.cc: In function ‘void nothing()’:
socc.cc:3:9: warning: statement has no effect [-Wunused-value]
false;
Upvotes: 6