对于循环使用C局部变量 [英] For-loop Local Variables in C

查看:100
本文介绍了对于循环使用C局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下code输出相同的内存位置每次?

Why does the following code output the same memory location everytime?

int x;
for (x = 0; x < 10; x++) {
    int y = 10;
    printf("%p\n", &y);
}

我认为存储位置应为每一个for循环运行时改变,变量是新的。

I thought that the memory location should change as each time the for-loop is run, the variable is new.

推荐答案

是的,你是绝对正确的内存位置的可能的变化。但它不必:)。在每次迭代的旧变量破坏和新的一个是创造在同一个地方。虽然任何像样的编译器优化了不必要的动作掉

Yes, you are absolutely right that the memory location could change. But it doesn't have to :). In each iteration the old variable is "destroyed" and a new one is "created" at the same place. Although any decent compiler would optimize the unnecessary "actions" away

这篇关于对于循环使用C局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆