我不知道为什么在运行时未在for循环条件下评估sizeof运算符?我正在尝试使用不同的c编译器编写此简单代码,但始终不输出任何内容。但是,如果我将sizeof(i)替换为4,则可以正常工作:
for(int i = -2; i <= 4; i ++)
/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
int main()
{
for(int i = -2; i <= sizeof(i); i++)
printf("Hello World");
return 0;
}
问题是,sizeof()
运算符的结果是类型size_t
,这是无符号类型。
接下来,在比较中,根据关节运动促进规则的i <= sizeof(i)
,作为有符号值的-2
被提升为无符号值,产生巨大的值,并将条件评估为假。因此不满足循环条件,并且不执行循环主体。
通过调试器运行程序,并在每个步骤中看到值,一旦在比较中看到提升的值,对您来说就会更加清楚。
sizeof
产生unsigned
类型变量(size_t
)的值。 i
转换为该类型,并且比较执行为
(size_t)-2 <= 4
类似于4000000000 < 4
您需要将sizeof(i)转换为int。应该可以解决问题。
所以只需将for(int i = -2; i <= sizeof(i); i++)
替换为for(int i = -2; i <= (int) sizeof(i); i++)
sizeof()返回size_t,这是一个无符号类型。您可以尝试使用以下代码:
#include<stdio.h>
int main()
{
int i=-2,j;
j=(int)sizeof(i);
for(i=-2;i<=j;i++)
printf("HELLO\n");
return 0;
}
您可以将sizeof()输入类型转换为int。