今天看下属的代码才发现的,之前还真没碰到过。
#include <stdio.h> int main() { for (int i=0; i<10; ++i) { for (int i=0; i<10; ++i) { ; } int x = i; } return 0; } |
gcc编译:
debian:~$ gcc t.cc t.cc: In function ‘int main()’: t.cc:10: warning: name lookup of ‘i’ changed t.cc:4: warning: matches this ‘i’ under ISO standard rules t.cc:6: warning: matches this ‘i’ under old rules |
vc编译:
D:\tmp>cl c.cc Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. c.cc c.cc(10) : warning C4258: 'i' : definition from the for loop is ignored; the def inition from the enclosing scope is used c.cc(6) : definition of 'i' ignored c.cc(4) : definition of 'i' used |
如果去掉int x = i;那一行,就没有这个warning。
这个倒也比较好理解,按照旧规则和新规则,int x=i有两种不同的解释,分别对应两个不同scope里的i。所以就给个warning。