简体   繁体   中英

Comma operators and assignment operators - return values

以下代码段得到32的输出,我有点混淆为什么?

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

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

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.

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM