c - 为什么这段 C 代码可以工作? (不应该)

标签 c comma-operator

我正在检查学生的作业。 任务是将英文字母的数量打印到控制台。 由于某种原因,他所做的事情有效(第 7 行):

 int main(void)
 {
     char first = 'A';
     char last = 'Z';
     int amount = 0;

     amount = ("%d - %d", last - first + 1);
     printf("The amount of letters in the English alphabet is %d\n", amount); 
     return(0);
 }

看到它后,我尝试将其他内容放在括号中而不是“%d - %d”。无论我在那里放什么以及有多少个逗号,它只会采用最后一个逗号后面的内容(这是正确的句子)。

那里到底发生了什么?

最佳答案

这是 comma operator 的使用示例之一。如果出现

 ("%d - %d", last - first + 1);

对逗号运算符 ( "%d - %d" ) 的 LHS 操作数进行求值,结果被丢弃,然后对 RHS ( last - first + 1 ) 进行求值并作为结果返回。然后将结果分配给 amount因此,你有 amount保存操作结果last - first + 1 .

引用C11 ,第 §6.5.17 章,逗号运算符

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

FWIW,在这种情况下,"%d - %d"只是另一个字符串文字,它不带有任何特殊含义。

关于c - 为什么这段 C 代码可以工作? (不应该),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714761/

相关文章:

c - ablkcipher_request_set_callback 有什么作用?

c - 编译器在 double 之后跳过 scanf 语句进行字符输入。为什么会这样?

c - 如何在C中遍历链表而不破坏它?

c++ - 在 C++ 线程中使用逗号和分号

c++ - 什么时候逗号运算符不充当逗号运算符?

c - 仅读取和打印正数组索引

c - 我做了什么? If 语句有效....有点

C 标准 - 逗号运算符语法

c - 逗号运算符 , 有什么作用?

javascript - for 循环中带有声明的逗号运算符