TITLE: Declaration or expression - that is the question PROBLEM: scvicato@unidhp.uni-c.dk (Scanview Software) The following code shows an apparent confusion on the part of either a specific C++ compiler (two were tested) or with C++ in general. class Bob { int x; public: Bob( void ) { x = 1; } Bob( int y ) : x(y) { } }; void main( void ) { int n = 6; Bob(6); // temporary instance of Bob initialized to 6 Bob(n); // This temporary instance fails to compile. // The compiler thinks this line is equivalent to: Bob n; Bob((int)n); // However this works by typecasting an int to an int! } RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 29 June 95 [ ... ] The compilers are correctly implementing a C++ rule. It is possible to write a C++ statement which could be interpreted as either a declaration-statement or an expression-statement. The C++ rule is (perhaps arbitrarily) that if a statement CAN BE interpreted as a declaration, it IS a declaration, and is NOT an expression. It isn't possible to declare an anonymous temporary variable. That is, creation of an anonymous temporary variable requires an expression, and is not a declaration. "Bob(6);" cannot be interpreted as a declaration, so it must be a cast-expression. The value 6 is converted to a Bob, and the result is discarded. "Bob(n);" can be interpreted as declaring local variable 'n' to be type Bob. Extra parens are allowed around the declarator (the name of variable 'n' in this case). Therefore, this is a declaration of 'n' and not an expression. "Bob((int)n);" cannot be interpreted as a declaration, so it must be a cast-expression. (You might think that it could possibly be interpreted as a declaration of function Bob taking one int parameter, but the parens around 'int' make that impossible. No type specifier can begin with a left paren.) The rule is almost never a problem in real code unless you are doing something very unusual. I consider creating an anonymous temporary variable for the sole purpose of its side effects unusual and ill-advised. It is going to be confusing to anyone who reads the code. Create a named local variable if you wish, and document that you are doing so for its side effects.