What is C Operand Evaluation Order- Best C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Chapter 4 · Operators and Expressions

C Operand Evaluation Order

Why C does not promise which operand runs first, and the four operators that do

Ch 4
Operators and Expressions
4
Worked programs
Beginner
Level

This lecture of our free C programming course answers a question that surprises almost every beginner: when C adds two things together, which one does it evaluate first? Precedence told you how an expression is grouped. It never told you in what order the pieces are computed.

For plain values the order makes no difference. The moment an operand has a side effect, such as ++x, a function call that prints, or a hardware register read that clears a flag, the order changes the program. This free C tutorial separates the three cases you must know: unspecified, undefined and guaranteed. We prove each one by compiling with both GCC and Clang, which, as you will see, disagree with each other. This knowledge is essential for embedded C programming, where reading a register often changes the register.

What You Will Learn in This Free C Programming Course Lecture

  • Why precedence and associativity do not decide the order of evaluation of operands
  • The difference between unspecified behaviour and undefined behaviour
  • Which four operators guarantee that the left operand is evaluated first
  • How short-circuit evaluation skips the right operand of && and ||
  • How GCC and Clang produced different results from the same source
  • How to write expressions whose result never depends on the compiler

Prerequisites for This Free C Programming Course Lecture

  • Increment and decrement operators, prefix and postfix
  • Logical AND, OR and the conditional operator from earlier lectures
  • The previous lecture on expression evaluation

Precedence Does Not Decide Evaluation Order

Consider y = f() + g();. Precedence tells you the + is evaluated before the assignment. Associativity tells you how a chain like f() + g() + h() is grouped. Neither tells you whether f() or g() runs first. The C standard deliberately leaves that to the compiler, so that the optimiser can pick the fastest order for the target CPU.

Grouping is fixed. Evaluation order is not.
grouping f() + g()  → one + node with two operands
order A f() first, then g()  → legal
order B g() first, then f()  → also legal
result same value if no side effects  → different if there are

The original textbook example is y = (++x) + (--x); with x = 5. The book says the answer is 11 if the first operand goes first and 9 if the second does, and advises avoiding such code. The advice is right, but the modern standard says something stronger, as the next section shows.

Unspecified Behaviour Versus Undefined Behaviour

TermMeaningExample in this lectureIs the program valid?
UnspecifiedThe standard allows several orders and the compiler need not document whichThe order of two function calls in f() + g()Yes, but output may differ between compilers
UndefinedThe standard places no requirements at all on the resultTwo unsequenced changes to the same variableNo. Anything may happen
GuaranteedThe standard fixes the orderLeft operand of &&, ||, ?:, ,Yes, portable

The rule behind the second row is this: if one expression changes a variable and, between two sequence points (or without one operation being sequenced before the other), changes it again or reads it for any purpose other than computing the new value, the behaviour is undefined. Let us watch it happen.

#include <stdio.h>

int main(void)
{
    int x = 5;
    int y = (++x) + (--x);   /* two unsequenced changes to x: undefined behaviour */

    printf("x = %d, y = %d\n", x, y);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra e21_2.c -o e21_2_gcc && ./e21_2_gcc
src/e21_2.c: In function 'main':
src/e21_2.c:6:22: warning: operation on 'x' may be undefined [-Wsequence-point]
    6 |     int y = (++x) + (--x);   /* two unsequenced changes to x: undefined behaviour */
      |                     ~^~~~
x = 5, y = 10
$ clang -std=c11 -Wall -Wextra e21_2.c -o e21_2_clang && ./e21_2_clang
src/e21_2.c:6:14: warning: multiple unsequenced modifications to 'x' [-Wunsequenced]
    6 |     int y = (++x) + (--x);   /* two unsequenced changes to x: undefined behaviour */
      |              ^       ~~
1 warning generated.
x = 5, y = 11

Same source, same machine, different answers: GCC printed y = 10 and Clang printed y = 11. Neither is a bug in the compiler, because the program has undefined behaviour and no answer is required. Both compilers also warned you at compile time. Read warnings like this as errors.

Watching the Order With Function Calls

Function calls with a visible side effect, here a printf, let us observe the order directly. There is no undefined behaviour here, because function calls cannot overlap. The order is simply unspecified.

#include <stdio.h>

static int trace(const char *name, int value)
{
    printf("  evaluating %s\n", name);
    return value;
}

static void show3(int p, int q, int r)
{
    printf("  show3 received %d %d %d\n", p, q, r);
}

int main(void)
{
    printf("operands of '+':\n");
    int sum = trace("LEFT", 10) + trace("RIGHT", 20);
    printf("  sum = %d\n", sum);

    printf("arguments of a function call:\n");
    show3(trace("first", 1), trace("second", 2), trace("third", 3));
    return 0;
}
$ gcc -std=c11 -Wall -Wextra e21_1.c -o e21_1 && ./e21_1
operands of '+':
  evaluating LEFT
  evaluating RIGHT
  sum = 30
arguments of a function call:
  evaluating third
  evaluating second
  evaluating first
  show3 received 1 2 3
$ clang -std=c11 -Wall -Wextra e21_1.c -o e21_1 && ./e21_1
operands of '+':
  evaluating LEFT
  evaluating RIGHT
  sum = 30
arguments of a function call:
  evaluating first
  evaluating second
  evaluating third
  show3 received 1 2 3
TestGCC 13.3Clang 18.1
Operands of +LEFT, then RIGHTLEFT, then RIGHT
Arguments of show3(...)third, second, firstfirst, second, third
(++x) + (--x) with x = 5x = 5, y = 10x = 5, y = 11

Do not copy these results into your head as rules

These runs were on x86-64 Ubuntu 24.04 with no optimisation. A different version, optimisation level or target such as ARM Cortex-M can print a different order. The only safe conclusion is that the order of function arguments is unspecified, and many compilers evaluate them right to left.

The Four Operators With a Guaranteed Order

C guarantees a left-to-right evaluation for exactly four operators. In the standard’s wording there is a sequence point after the first operand, so every side effect of the left operand is complete before the right one starts.

OperatorGuaranteeWhat can be skipped
a && ba first. If a is 0, the result is 0b is not evaluated when a is false
a || ba first. If a is non-zero, the result is 1b is not evaluated when a is true
c ? x : yc first, then only one of x or ythe branch not chosen
a, ba first, discarded, then b. Value is bnothing

A fifth rule worth knowing: all arguments of a function are fully evaluated before the function body starts, but the order among the arguments is still unspecified. The program below exercises all four guaranteed operators. Each probe prints its tag when it runs, so skipped operands simply never appear.

#include <stdio.h>

static int probe(const char *tag, int value)
{
    printf("  %s ", tag);
    return value;
}

int main(void)
{
    int r;

    printf("&&  with false left : ");
    r = probe("A", 0) && probe("B", 1);
    printf("-> %d\n", r);

    printf("&&  with true left  : ");
    r = probe("A", 1) && probe("B", 1);
    printf("-> %d\n", r);

    printf("||  with true left  : ");
    r = probe("C", 1) || probe("D", 1);
    printf("-> %d\n", r);

    printf("||  with false left : ");
    r = probe("C", 0) || probe("D", 1);
    printf("-> %d\n", r);

    printf("?:  condition true  : ");
    r = probe("cond", 1) ? probe("yes", 10) : probe("no", 20);
    printf("-> %d\n", r);

    printf("?:  condition false : ");
    r = probe("cond", 0) ? probe("yes", 10) : probe("no", 20);
    printf("-> %d\n", r);

    printf(",   comma operator  : ");
    r = (probe("p", 1), probe("q", 2), probe("r", 3));
    printf("-> %d\n", r);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra e21_3.c -o e21_3 && ./e21_3
&&  with false left :   A -> 0
&&  with true left  :   A   B -> 1
||  with true left  :   C -> 1
||  with false left :   C   D -> 1
?:  condition true  :   cond   yes -> 10
?:  condition false :   cond   no -> 20
,   comma operator  :   p   q   r -> 3

Read the output line by line. With a false left side, && never runs B. With a true left side, || never runs D. The conditional operator runs the condition, then exactly one branch. The comma operator runs everything and returns the last value, 3. Both compilers produced identical output for this program, because the behaviour is guaranteed rather than chosen.

Short-circuit flow of A && B and C || D
A && B A is 0  → skip B, result 0
A && B A is non-zero  → evaluate B, result is B != 0
C || D C is non-zero  → skip D, result 1
C || D C is 0  → evaluate D, result is D != 0

Short-Circuit Evaluation in Embedded C Programming

Short-circuiting is a feature you rely on every day, for example in if (a != 0 && b / a > 2), where the division can never happen with a zero divisor, or in a null-pointer guard that tests the pointer before it uses the pointer. In firmware the same feature can also cause a bug.

Many peripherals clear an interrupt flag when you read its status register. The program below simulates two such registers. Compare testing both with || against reading each register into a variable first.

#include <stdio.h>

/* Pretend each read of a status register clears its interrupt flag. */
static int primary_pending   = 1;
static int secondary_pending = 1;

static int read_primary(void)
{
    int v = primary_pending;
    primary_pending = 0;
    printf("  primary read   -> %d (flag cleared)\n", v);
    return v;
}

static int read_secondary(void)
{
    int v = secondary_pending;
    secondary_pending = 0;
    printf("  secondary read -> %d (flag cleared)\n", v);
    return v;
}

int main(void)
{
    printf("using ||  :\n");
    if (read_primary() || read_secondary())
        printf("  work needed\n");
    printf("  secondary flag still pending? %d\n\n", secondary_pending);

    primary_pending = 1;
    secondary_pending = 1;

    printf("read both first, test later:\n");
    int p = read_primary();
    int s = read_secondary();
    if (p || s)
        printf("  work needed\n");
    printf("  secondary flag still pending? %d\n", secondary_pending);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra e21_4.c -o e21_4 && ./e21_4
using ||  :
  primary read   -> 1 (flag cleared)
  work needed
  secondary flag still pending? 1

read both first, test later:
  primary read   -> 1 (flag cleared)
  secondary read -> 1 (flag cleared)
  work needed
  secondary flag still pending? 0

With ||, the secondary register is never read, so its flag stays pending. The interrupt that set it will fire again, or worse, be lost if the peripheral latches only one event. Reading both registers into variables first is clearer and has no hidden skip.

Rule of thumb for hardware

If an operand has a side effect that must always happen, do not put it on the right side of &&, || or ?:. Perform it in its own statement.

How to Write Order-Independent Expressions

  1. Change a variable at most once in one expression, and do not read it elsewhere in that same expression.
  2. Never put two calls that share state in the same expression and expect a particular order.
  3. When order matters, split the work into separate statements. A semicolon is a sequence point.
  4. Use &&, || or the comma operator only when you want the left-to-right guarantee and understand which operand may be skipped.
  5. Compile with -Wall -Wextra. GCC reports -Wsequence-point and Clang reports -Wunsequenced.

Common Mistakes and Troubleshooting

MistakeWhy it is a problemFix
Using i++ twice in one expressionUndefined behaviourUse separate statements
Calling f(i++, i++)Unsequenced changes plus unspecified argument orderCompute values into temporaries first
Relying on printed order of argumentsIt differs between compilers and optimisation levelsPrint in separate calls
Putting a register read after ||The read may be skippedRead into a variable first
Assuming left to right because the book showed itOnly four operators guarantee itKnow the four

Best Practices, Performance and Security

  • Prefer one side effect per statement. It costs nothing in speed, because the compiler optimises across statements.
  • Undefined behaviour lets the optimiser assume the case never happens, so it may delete checks around it. At -O2 the same code can change meaning.
  • Evaluation-order bugs are a recurring source of security vulnerabilities, because they work on the developer’s machine and fail on the customer’s.
  • Treat every compiler warning about sequence points as a build failure in firmware projects.

Key Takeaways From This Free C Programming Course Lecture

  • Precedence decides grouping, not evaluation order.
  • The order of operands and function arguments is unspecified, so never depend on it.
  • Two unsequenced modifications of one variable are undefined behaviour. The result may differ between compilers, as GCC and Clang showed here.
  • Only &&, ||, ?: and the comma operator guarantee left-to-right order.
  • Short-circuiting may skip side effects. Do not hide required register reads on the right-hand side.

Practice Questions

Q1. Is int r = n++ + n++; a valid way to add the old and the next value of n?

No. It modifies n twice without a sequence point, so the behaviour is undefined. Write two statements instead.

Q2. Is if (a != 0 && b / a > 2) safe when a is 0?

Yes. The left operand is evaluated first and is false, so the division is never evaluated.

Q3. What is the value of (f(), g()), and which call runs first?

The comma operator guarantees f() runs first. The value is the return value of g().

Q4. A function call show3(a(), b(), c()) prints in a different order on two compilers. Is either one wrong?

No. The order of argument evaluation is unspecified, so both are conforming.

Interview Questions on Order of Evaluation

What is a sequence point?

A point in execution at which all side effects of earlier evaluations are complete and none of the later ones have started. Examples are the end of a full expression, after the left operand of &&, ||, ?: and the comma operator, and before a function call after its arguments are evaluated.

What is the difference between unspecified and undefined behaviour?

Unspecified means the standard allows several valid outcomes and the program is still valid. Undefined means the standard imposes no requirement, so the program is invalid and may do anything.

Why can short-circuit evaluation hide bugs in firmware?

The skipped operand may contain a side effect such as a status register read, which then never happens.

Conclusion

You now know the line between three kinds of behaviour. Grouping comes from precedence and associativity. Order comes from the standard only in four cases. Everywhere else, assume the compiler is free to pick, and write code that does not care. Two compilers gave two answers for the same program in this lecture, and that is exactly why portable embedded code avoids these expressions. Continue with this free C programming course to practise tracing expressions and spotting the invalid ones.

Frequently Asked Questions

In what order does C evaluate the operands of an operator?

It is unspecified for most operators. Only &&, ||, ?: and the comma operator guarantee that the left operand is evaluated first.

Is y = (++x) + (–x) valid C?

It compiles, but it has undefined behaviour because x is modified twice without a sequence point. In this lecture GCC gave 10 and Clang gave 11 for x = 5.

What is short-circuit evaluation in C?

With && the right operand is skipped when the left is false. With || it is skipped when the left is true.

Does a free C programming course cover undefined behaviour?

A good one should. This free C programming course from EmbeddedPathashala explains unspecified and undefined behaviour with compiled examples because both cause real firmware bugs.

What is the order of evaluation of function arguments in C?

It is unspecified. The arguments are all evaluated before the call, but in any order. GCC evaluated them right to left and Clang left to right in our test.

Which compiler options detect evaluation-order problems?

GCC reports -Wsequence-point as part of -Wall. Clang reports -Wunsequenced.

Topics Covered

free C programming coursefree C tutorialC programming for embedded systemsembedded C programmingfree embedded C courseorder of evaluationshort-circuit evaluationundefined behavioursequence point

Keep Going With the Course

Next we practise tracing expressions with a set of solved exercises.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →