简体   繁体   English

if条件下的C ++静态和非静态变量声明

[英]C++ static and non-static variable declaration in if condition

The following if conditions compile in Visual Studio C++: 如果条件在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. 另一方面,gnu编译器只编译第一个。 From testing it seems like the scope of the variable is just within the if condition. 从测试来看,似乎变量的范围恰好在if条件下。

However, since Visual studio compiles both version, I was wondering if there are any differences? 但是,由于Visual Studio编译了两个版本,我想知道是否有任何差异?

According to C++ standard, the GNU is correct and VisualStudio is doing it wrong. 根据C ++标准,GNU是正确的,VisualStudio做错了。 Following 6.4/1: 遵循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 . 允许使用type-specifier-seq ,它不能包含存储类说明符,例如static To see what a type-specifier-seq can have, read this . 要查看type-specifier-seq可以有什么,请阅读此内容

This is valid as of C++11: 这在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. 一个缺陷在标准允许却在条件来定义类型,而这已修复了C ++ 14,但由于缺陷的GCC团队似乎已经举行了一个bug修正 ,看起来像它可能会解决这个问题,因为好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM