Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning multiple integers separated by comma to an int in C - Why does that work? What for? [duplicate]

I saw this in an exam and when I tried it out I was surprised. I tried it online and it works too. So I think it is the C language.

Why is that working? What is the use case for such an assignment syntax?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    int i = (1,2,3,4,5);
    printf("%d", i);
    return 0;
}
like image 699
Ely Avatar asked Jul 30 '15 01:07

Ely


2 Answers

These are not "multiple integers", but a comma operator. The whole parenthesised part is a single expression with each sub-expression (separated by commas) evaluated strictly from left to right. The results of all but the rightmost subexpression are ignored. The result of the whole expression is that of the last (rightmost) expression. Here it is the integer value 5.

Note that this operator is mostly used where only a single expression is allowed to add further side-effects. E.g. in a loop like:

int cnt = 0;
for ( const char *cp = "Hello" ; *cp != '\0' ; cp++, cnt++ )  ;

This counts the number of characters in a C-string, incrementing the pointer and cnt after each iteration. The results are ignored here.

So, this is in no way related to tuples or similar like in Python. There are actually no cases the usage of this operator is unavoidable and it should be used with caution — and some coding standards forbid its usage.

like image 75
too honest for this site Avatar answered Jan 04 '23 05:01

too honest for this site


That's the comma operator at work. It evaluates the expression on its left-hand side, creates a sequence point, discards the value of the expression, then evaluates the expression on the right-hand side, and returns that as the value. When there are multiple expressions as in the example, then each is evaluated in turn and only the last is kept. With the sample, the compiler does the evaluation because every value is known at compile time. Note that the argument list to a function is not a use of the comma operator.

That isn't a valid use-case for the comma operator. What might be a more nearly valid use-case would be some operations with side-effects (such as function calls) that need to be sequenced and the final value assigned:

int i = (getchar(), getchar(), getchar());

This sets i to the third character in standard input, or EOF if there are not three characters left in the standard input to be read. Still not a realistic use-case, but better than assigning a list of constants.

like image 29
Jonathan Leffler Avatar answered Jan 04 '23 06:01

Jonathan Leffler