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