The following C++ code does nothing (using GCC 4.4.3) – it does not print the text:
struct MyStruct { MyStruct() { cout << "Hello" << endl; } };
void foo() {
MyStruct ();
}
I think this is not so obvious… Let alone the danger of forgetting to give a variable name. Is there a compiler option/warning to forbid compilation of such code or is there any hidden secret behind allowing it?
Edit: I am sorry. The version above MyStruct(); acutally prints. The version which is not printing is:
void bar() {
MyStruct a();
}
So now I am a bit confused.
This is not a declaration, because in
MyStruct ();, theMyStructwould be part of the decl-specifier-seq and forms a type-name therein. And then()can only be a function-declarator. This requires that there is a declarator-id specified, which in your case is not. A special syntactical form is needed to allow such a syntax in declaring a constructor. But such syntactical exceptions are not made in a declaration-statement.So this construct cannot be a declaration. It is parsed as an expression which specifies a functional cast creating a temporary of type
MyStruct.If the compiler does not print Hello it is either non-conforming or you are not calling
fooin your program.Your edit also does not specify a declaration without a name. It instead specifies a declaration that does have a name. It declares a function that is called
a. The compiler has no way that you meant something else by this.It could in an effort deduce this by having a recovering rule when it later discovers errors in your code such as the following
If you have this in your code to try and call a member function and “a” is a function, the compiler could check to see if
MyStructcontains a memberfsuch that this expression is well-formed. But what if you just forgot to place parentheses? The following would be valid for the above declared function that returns aMyStruct, assuming a suitably declared memberf.So in effect, the compiler can’t really know what you mean.