SelfInitialization

遇到一段代码,觉得很迷糊,觉得不对。于是做了个测试,代码如下

#include <stdio.h>
int main()
{
int flag = flag ;//flag哪里定义?
flag = 1;
printf(
"flag is %d\n",flag);
}

在gcc下竟然可以通过,输出也是对的。

如果不赋值的话,flag输出的为无意义值

于是产生为什么flag不提示未定义的疑问,这是什么语法?gcc连警告都不提。

水木上的牛人给出了网址

http://cpp-style.info/Addison.Wesley-CPP.Gotchas-Avoiding.Common.Problems.in.Coding.and.Design/0321125185_ch02lev1sec9.html

说是 Self-Initialization,解答上有如下的话

/*
It's undefined. In C++, a name comes into scope before its initializer is parsed,
so any reference to the name within the initializer refers to the name being declared!
Not many programmers will compose as strange a declaration as the one above,
but it's possible to cut and paste your way into trouble
*/
翻译出来就是,该行为未定义。

原文地址:https://www.cnblogs.com/westfly/p/2003881.html