这个自初始化有效吗?
我有这个问题,我之前考虑过,但我认为回答这个问题并不简单。
int x = x + 1;
int main() {
return x;
}
我的问题是程序的行为是否已定义或未定义(如果它完全有效)。如果已定义,x
的值在 main
中是否已知?
I have this question, which i thought about earlier, but figured it's not trivial to answer
int x = x + 1;
int main() {
return x;
}
My question is whether the behavior of the program is defined or undefined if it's valid at all. If it's defined, is the value of x
known in main
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我很确定它已定义,并且 x 的值应该为 1。§3.6.2/1 说:“具有静态存储持续时间 (3.7.1) 的对象应在任何其他初始化发生之前进行零初始化 (8.5)。 ”
之后,我认为一切都非常简单。
I'm pretty sure it's defined, and x should have the value 1. §3.6.2/1 says: "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place."
After that, I think it's all pretty straightforward.
这段代码绝对不干净,但对我来说它应该可以预见地工作。
int x
将变量放入数据段中,该数据段在程序开始时定义为零。在main()
之前,调用静态初始化器。对于x
,即代码x = x + 1
。x = 0 + 1 = 1
。因此 main() 将返回 1。如果 x 是在堆栈上分配的局部变量,则代码肯定会以不可预测的方式工作。与数据段不同,堆栈状态几乎可以保证包含未定义的垃圾。
This code is definitely not clean, but to me it should work predictably.
int x
puts the variable into the data segment which is defined to be zero at the program start. Beforemain()
, static initializers are called. Forx
that is the codex = x + 1
.x = 0 + 1 = 1
. Thus the main() would return 1.The code would definitely work in unpredictable fashion if
x
is a local variable, allocated on stack. State of stack, unlike the data segment, is pretty much guaranteed to contain undefined garbage.'x' 变量存储在 .bss 中,加载程序时会用 0 填充。因此,当程序加载到内存中时,“x”的值为 0。
然后在调用 main 之前,执行“x = x + 1”。
我不知道它是否有效,但行为并非未定义。
The 'x' variable in stored in the .bss, which is filled with 0s when you load the program. Consequently, the value of 'x' is 0 when the program gets loaded in memory.
Then before main is called, "x = x + 1" is executed.
I don't know if it's valid or not, but the behavior is not undefined.
在 main 调用之前 x 必须初始化为 0,因此它的值必须为 1,当您输入 main 时,您将返回 1。这是一个已定义的行为。
Before the main call x must be initialized to 0 therefore it's value must be 1 one you enter main, and you will return 1. It's a defined behavior.