rtpax
rtpax

Reputation: 1777

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?

Upvotes: 3

Views: 98

Answers (2)

chqrlie
chqrlie

Reputation: 144740

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.

Upvotes: 6

user8478952
user8478952

Reputation:

The only way to force the order of evaluation is to use separate statements. Compilers can use whatever order is deemed necessary. So for function calls f1() + f2() + f3(); any of one of those function calls could be called before the other. The only influence you can have on that statement is what to do with the returns from those functions. So in short, just use separate statements. Most likely for whatever you're doing, putting the calls in a loop should do fine.

Decent reference: http://en.cppreference.com/w/c/language/eval_order

Upvotes: 1

Related Questions