c++ - 为什么输出不是预期的那样?

标签 c++ c

一直在经历这段代码:

#include<cstdio>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {1,2,3,4,5,6,7};

int main()
{
    signed int d;
    printf("Total Elements in the array are => %d\n",TOTAL_ELEMENTS);
    for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
        printf("%d\n",array[d+1]);
    return 0;
}

现在显然它没有进入 for 循环。 什么原因?

最佳答案

原因是在 C++ 中你得到了隐式提升。尽管d当您将它与 (TOTAL_ELEMENTS-2) 进行比较时,它被声明为已签名(由于 sizeof 而未签名),d被提升为无符号。 C++ 有非常具体的规则,基本上声明 d 的无符号值将是一致的无符号值 mod numeric_limits<unsigned>::max() .在这种情况下,结果是最大可能的无符号数,它明显大于比较另一侧的数组大小。

请注意,某些编译器(如 g++(带 -Wall))可以被告知对此类比较发出警告,因此您可以确保代码在编译时看起来正确。

关于c++ - 为什么输出不是预期的那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5356925/

相关文章:

C代码调用程序集: infinite loop

c++ - Qt 5.12.0 MinGW 7.3 w64从windows 64交叉编译到windows x86

c++ - function_object 在 for_each 之后丢失了数据成员的值

c++ - 如何对类的 const 实例使用打印运算符?

c++ - S60 3rd ed Emulator 在 Windows 7 中启动后立即终止

c - 在 C 上加载 BMP 文件时出错

c - 在 C 中实现双堆栈以在命令行上计算数学表达式。(段错误)

c - 在 chars.exe : 0xC0000005: Access violation reading location 0x00000004 中的 0x011414CE 抛出异常

c++ - 凡尔康错误 : Cannot submit cmd buffer using deleted buffer 0x0

c - libcjson.so : cannot open shared object file: No such file or directory