Ege
Ege

Reputation: 97

C++ static and non-static variable declaration in if condition

The following if conditions compile in Visual Studio C++:

if(int x = 5) { std::cout << x; }                  1

and

if(static int x = 5) { std::cout << x; }           2

On the other hand the gnu compiler only compiles the first one. From testing it seems like the scope of the variable is just within the if condition.

However, since Visual studio compiles both version, I was wondering if there are any differences?

Upvotes: 4

Views: 165

Answers (2)

user657267
user657267

Reputation: 21030

This is valid as of C++11:

condition: 
  expression 
  attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause 
  attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

A defect in the standard however allowed types to be defined in conditions, and this has been fixed for C++14, although due to the defect the GCC team seems to have held off on a bugfix that looks like it might fix this issue as well.

Upvotes: 2

masoud
masoud

Reputation: 56539

According to C++ standard, the GNU is correct and VisualStudio is doing it wrong. Following 6.4/1:

condition:
    expression
    type-specifier-seq declarator = assignment-expression

It is allowed to use type-specifier-seq and it can not contain storage class specifier such as static. To see what a type-specifier-seq can have, read this.

Upvotes: 3

Related Questions