C程序的困惑输出

标签 c for-loop output

如果我在 for 循环中定义 int x;,为什么编译器将 x 的值显示为 0 .但是,当从 for 循环中删除 int x 时,x 的值为 10

#include<stdio.h>
int main() {
    int x = 0, i;
    for(i = 1; i <= 10; i++) {
        int x;
        x = 10;
    }
    printf("%d", x);
}

最佳答案

如果您的 for 循环中有 int x,您将创建一个新的 x 变量。这意味着您的程序中实际上有两个 x 变量,一个可以从您的 main() 函数访问,另一个只能在 for-环形。如果您从 for 循环中访问 x,编译器将选择最接近的一个。

如果您的 for 循环中没有 int x,那么只有一个 x,您的程序将输出 10 .

关于C程序的困惑输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851557/

相关文章:

c++ - 如何将数组的元素传递给另一个?

c++ - 两个 for 循环和其中的一个 if 语句

python - 编写一个对数字列表求和的自定义求和函数

output - Labview多次使用输出

Java toString 方法 - 打印不正确

c - arm多少字节对齐?

c - MPI 和 C : loop through file of commands in file

C Ring Buffer 共享内存信号量 ReadPointer WritePointer Not Right

Javascript 在 for 循环中设置超时函数

c - 与打印文本和 NL 相比,先打印 NL,然后打印文本,然后手动刷新的任何原因?