bloop bloop - 10 months ago 54
C Question

Why does this C code work? (It shouldn't)

I am checking a student's homework.
The assignment is to print the amount of English letters to the console.
For some reason, what he did works (7th line):

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);

After seeing it, I tried putting other things in the brackets instead of "%d - %d". No matter what I put there and how many commas were there, it'd only take what's after the last comma (which is the correct sentence).

What is actually happening there?

Answer Source

This is one of the examples of usage of comma operator. In case of

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

the LHS operand of the comma operator ("%d - %d") is evaluated, result is discarded, then RHS (last - first + 1) is evaluated and returned as the result. The result, is then assigned to amount and thus, you have the amount holding the result of the operation last - first + 1.

Quoting C11, chapter ยง6.5.17, comma operator

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, in this case, "%d - %d" is just another string literal, it does not carry any special meaning.