comma - C data type declaration query -


in c programming language, on assigning 4,3 integer-type variable, like:

int a;  = 4,3; 

the variable receives value left of comma (i.e. a set 4 in example). on assigning parenthesized list, however, like

a = (4,3); 

, variable takes last value in comma-delimited list (3 in example).

what reason this?

c uses comma (,) in 2 distinct ways: element separator in compound constructs such array literals or lists of declarations, , binary operator. not have list-based assignment such higher-level languages do.

as operator, comma evaluates left-hand operand first, evaluates right-hand operand. value of overall expression second result. in ways complementary && , || operators, both of evaluate left-hand operands first, each of evaluates right-hand operand conditionally, depending on left-hand result.

the other key understanding observation equals sign (=) also operator. evaluates both operands, in unspecified order, , result same right-hand operand. modifying value of left-hand operand side effect.

the assignment operator has low precedence, comma operator has lowest precedence of all. therefore, if not use parentheses alter evaluation order, ...

a = 4,3; 

... equivalent ...

(a = 4), 3; 

. evaluates assignment first, yielding value 4 side effect of assigning value variable a. discards value , evaluates 3, yielding value 3 overall result. since whole thing not part of larger expression, result discarded.

on other hand, can override precedence suitable use of parentheses, in this:

a = (4, 3); 

. in case, comma operator evaluated first, yielding 3 result, , right-hand operand of assignment operator. assignment expression yields result 3, side effect of assigning value variable a.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -