c - 如果 char 是一个字节,这怎么不是未定义的行为

标签 c char int undefined-behavior

所以一个 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.

所以这种行为是明确定义的。

编辑:我意识到上面可能不是最好的例子,因为从 intchar 的转换将由实现定义(如果 char 默认为 unsignedsigned)。但是,它仍然表明这是定义的行为,而不是未定义的。

关于c - 如果 char 是一个字节,这怎么不是未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049074/

相关文章:

c++ - 什么是#pragma weak_import?

c++ - 按字符循环遍历 std 字符串的段错误

C 编程 - 将 const char 数组与用户输入进行比较

c - 向前移动 emacs 中的复合语句

c - 返回带有 char * 的字符串的内联声明

java - 在java中,有没有一种方法可以结合String.contain()和String.equals()来在给定另一个字符时打印出某个字符?

java - 按字符串中的值对字符串数组进行排序

java - String to int 给出 nullpointerexception

VBA 检查十进制值是否只有 2 个小数点。使用 Int() 时出错

c - 每行一个字数