所以一个 int 是四个字节,我只是不明白 C 是怎么知道在这种情况下让它工作的
随机函数显示我的意思
char strl[20];
int c, i=0;
puts("Enter a string up to 19 characters");
while((i<20) && (c=getChar())!="\n")
strl[i++]=c;
最佳答案
C 不是强类型语言,像这样的隐式转换很常见。
这个例子来自C11 draft standard 6.5.16.1与你的非常相似:
int f(void);
char c;
/* ... */
if ((c = f()) == -1)
/* ... */
the int value returned by the function may be truncated when stored in the char, and then converted back to int width prior to the comparison.
所以这种行为是明确定义的。
编辑:我意识到上面可能不是最好的例子,因为从 int
到 char
的转换将由实现定义(如果 char
默认为 unsigned
或 signed
)。但是,它仍然表明这是定义的行为,而不是未定义的。
关于c - 如果 char 是一个字节,这怎么不是未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049074/