Search code examples
coperator-precedence

Dictate order that operands are evaluated in c


The statement puts("a") + puts("b") is undefined. This is because it is not specified in the C Standard whether these ought to be executed left to right or right to left so you could get

a
b

or

b
a

Is there a clean way to dictate the order of operations in an expression?

The only thing I can think of is to use a compound statement such as

({
    int temp = puts("a");
    temp += puts("b");
    temp;
})

though this is non-portable and a little longer than I was hoping.

How could this best be achieved?


Solution

  • If you declare an int variable before the expression, you can force order portably with the comma operator while computing the sum inside an expression:

    int temp;
    ...
    
    (temp = puts("a"), temp + puts("b"))
    

    As specified in the C Standard:

    6.5.17 Comma operator

    Syntax

     expression:
         assignment-expression
         expression , assignment-expression
    

    Semantics

    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.

    Note however that the value of the expression will not be very useful given the semantics of puts(), as commented by Jonathan Leffler.