user288609
user288609

Reputation: 13015

Comma operators and assignment operators - return values

The following code segment get an output of 32, I am kind of confusing why?

 int i=(j=4,k=8,l=16,m=32); printf(“%d”, i); 

Upvotes: 4

Views: 468

Answers (5)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215211

Not really an "answer" but it should be noted that the main use of the comma operator is to sequentially evaluate expressions with side effects such as function calls, assignments, etc. in contexts where multiple statements would not be valid. The most essential use is in macros where you want the entire macro to "return a value" but perform more than one operation. The only other ways to accomplish this are using the gcc ({ /* multiple statements here */ }) extension or having the macro simply call a static/static inline function.

Another frequent use I find for the comma operator is with the for statement:

for (n=cnt; n; n--, d++, s++)

and when I have an if statement that needs to do two closely-connected operations and I don't want the visual clutter of braces:

if (condition) prefix="0x", len=2;

In these latter uses, the value of the result of the comma operator is not particularly useful, so it doesn't matter so much that it may be confusing to C beginners.

Upvotes: 0

deepseefan
deepseefan

Reputation: 3791

In other words, whatever in the bracket is evaluated first from left to right; and the right most expression is returned as an output of the bracket as the result int i gets the decimal value 32.

Upvotes: 2

Rich Adams
Rich Adams

Reputation: 26574

int i=(j=4,k=8,l=16,m=32); printf(“%d”, i); // Will give you 32
int i=(j=4,k=8,l=16); printf(“%d”, i); // Will give you 16
int i=(j=4,k=8,l=16,m=32,n=64); printf(“%d”, i); // Will give you 64

See the pattern?

Basically, i is being set to whatever the value of the last assignment in the braces is, since the , operator will evaluate each assignment in sequence but return the value of the last assignment made in your case above.

More generally, the , operator (comma operator) will evaluate a series of expressions in sequence and return the value of the last expression. So in your case, i is being assigned the value being assigned last in braces (since the return from an assignment, is the value being assigned), which is 32.

Upvotes: 4

codaddict
codaddict

Reputation: 454980

The comma operator is left associative.

It evaluates j=4 followed by k=8, followed by l=16 and finally m=32 and returns 32. Hence i gets the value of 32.

Upvotes: 4

relet
relet

Reputation: 7009

Start reading inside the first set of parentheses.

The comma operator evaluates each of several expressions subsequently. It returns the return value of the last expression - in this case, it is 32, because the return value of an assignment is the value assigned.

http://en.wikipedia.org/wiki/Comma_operator

Upvotes: 12

Related Questions