Order of Evaluating Function Arguments- Free Online 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 →

Order of Evaluating Function Arguments

Lecture 18 of our free embedded C course: why the order of argument evaluation is unspecified in C and how to write code that behaves the same on every compiler.

This lecture of our free embedded C course deals with a rule that surprises almost every beginner: C does not say in which order the arguments of a function call are evaluated. If you plan a career in embedded C programming, where one project is often built with different compilers and optimization levels, this rule matters a lot. In this part of the free C programming course you will see exactly where the trouble appears, how to recognize risky expressions, and how to rewrite them so the result never depends on the compiler.

What You Will Learn

  • What unspecified evaluation order means for function arguments
  • Why expressions with side effects on the same variable are dangerous
  • The difference between unspecified behavior and undefined behavior
  • How reading hardware registers inside argument lists can bite you
  • A clean pattern to make evaluation order explicit
  • Tools and compiler flags that detect these bugs

Prerequisites

You should know how a function call copies actual arguments into formal arguments, and you should understand the increment and decrement operators from the operators chapter of this free C tutorial.

The Rule in Plain Words

When a function is called with several arguments, each argument is an expression, and the compiler must evaluate all of them before the call happens. The standard guarantees that all argument evaluations finish before the function body starts. What it does not guarantee is the order among them. A compiler may go left to right, right to left, or interleave the work in a way that suits the target processor. It may even choose different orders in different places of the same program.

Evaluation of a Call With Two Arguments
call: f(A, B)
possible order 1 evaluate A → evaluate B → enter f
possible order 2 evaluate B → evaluate A → enter f
guaranteed: both finish before f starts

When It Does Not Matter

For most calls the order has no visible effect. If the arguments are plain variables, constants or pure arithmetic with no side effects, any order produces the same values.

int area = rect_area(width + 2, height - 1);

Here both expressions only read variables, so whichever is evaluated first, the function receives identical values. The trouble starts only when an argument changes something that another argument also uses.

When It Matters: Side Effects

A side effect is any change a piece of code makes besides producing a value: incrementing a variable, assigning to it, reading a device that clears on read, or calling a function that updates a global. Let us study the three common patterns.

Pattern 1: Two Calls With Side Effects on Shared State

#include <stdio.h>

static int counter = 0;

int next_id(void)
{
    counter = counter + 1;
    return counter;
}

void show_pair(int first, int second)
{
    printf("first=%d second=%d\n", first, second);
}

int main(void)
{
    show_pair(next_id(), next_id());
    return 0;
}

Both arguments call next_id, and each call changes the shared counter. If the compiler evaluates the left call first, the output is first=1 second=2. If it evaluates the right call first, the output is first=2 second=1. Both outputs are valid, and the same source can print either one depending on the compiler and its settings. The standard calls this unspecified behavior: the program is legal, but the result is not fixed.

Pattern 2: Modifying and Reading the Same Variable

int n = 4;
int r = combine(n, ++n);   /* risky */

This one is worse. The variable n is read in one argument and modified in another, with nothing that orders the two actions. Under the language rules this is undefined behavior, which means the standard places no limits at all on what happens. Textbooks often explain it as “the answer may differ across compilers”, and that is true, but the full truth is stronger: the program is simply wrong, and a future compiler version may produce a completely different result.

TermMeaningExample in arguments
UnspecifiedSeveral results are allowed, one will occurf(next_id(), next_id())
UndefinedAnything may happen, program is invalidf(n, ++n)
Well definedExactly one resultf(n, n + 1)

Pattern 3: Several Increments in One printf

The printf function is a function like any other, so the same rule applies to its arguments. A line that prints a variable together with its pre and post increments gives no dependable output.

int k = 20;
printf("%d %d %d\n", k, k++, --k);   /* do not write this */

Each of the three arguments touches k, and the changes are unordered. Different compilers print different numbers, and some warn you. Never use such lines in real code, not even for testing.

An Embedded Example That Hurts

Imagine a UART whose data register clears itself when read. A careless developer writes this:

process_pair(uart_read_byte(), uart_read_byte());

The first byte received is meant to be the command and the second the value, but the compiler may evaluate the right argument first, swapping them. The code might work on your desktop test build and fail on the target, or the other way around. Reading hardware in argument lists is a classic embedded bug, and fixing it takes only two extra lines.

The Safe Pattern: Make the Order Explicit

Statements end with a sequence point, so the compiler must finish one statement before the next one starts. Use temporary variables to force the order you want.

#include <stdio.h>

static int counter = 0;

int next_id(void)
{
    counter = counter + 1;
    return counter;
}

void show_pair(int first, int second)
{
    printf("first=%d second=%d\n", first, second);
}

int main(void)
{
    int a = next_id();     /* runs first, guaranteed  */
    int b = next_id();     /* runs second, guaranteed */
    show_pair(a, b);
    return 0;
}
first=1 second=2

Now the output is the same under every compiler and every optimization level. The intent is also clearer to anyone reading your code later.

Risky Style Versus Safe Style
risky one statement → many side effects → order chosen by compiler
safe statement 1 → statement 2 → call with plain variables

One simple rule

If an argument changes something, no other argument in the same call should read or change that thing. Better still, do the changing in a separate statement before the call.

Related Cases Beyond Function Calls

The same lack of ordering applies to operands of most operators, for example in x = i + i++ or in an array index like arr[i] = i++. The rules are different for a few operators that do define an order: logical AND, logical OR, the conditional operator and the comma operator all evaluate left to right with a sequence point. The commas separating function arguments, however, are not the comma operator, so they give no ordering at all.

ConstructOrder guaranteed?
Function arguments, f(a, b)No
Operands of + and *No
Logical AND and ORYes, left to right with short circuit
Comma operatorYes, left to right
Conditional operatorCondition first, then one branch
Separate statementsYes

Common Mistakes and Troubleshooting

Assuming left to right: It is common on some compilers, but it is not guaranteed by C.

Testing on one compiler only: A result that looks fine on your laptop may differ on the target toolchain.

Compact clever code: Packing increments into call arguments saves a line and costs hours of debugging.

Hardware reads in arguments: Registers that clear on read must be read in separate statements.

gcc -Wall -Wextra -Wsequence-point -fsanitize=undefined main.c

The warning flag reports many unsequenced modifications at compile time, and the sanitizer can catch some at run time during testing.

Best Practices

  • Keep call arguments free of side effects
  • Use named temporaries when order matters
  • Review coding standards such as MISRA C, which restrict side effects in expressions
  • Build with at least two compilers or optimization levels in your test pipeline
  • Read hardware registers in clearly ordered statements

Summary and Key Takeaways

  • C evaluates all arguments before the call, but in no promised order
  • Side effects on shared state give unspecified results
  • Modifying and reading the same variable in one call is undefined behavior
  • Separate statements guarantee order and clarity
  • Embedded projects feel this rule strongly because of multiple toolchains

With this lecture of our free C programming course, you can now spot one of the best known traps in the language. Our next lecture covers the most special function of all: main.

Frequently Asked Questions

In what order are function arguments evaluated in C?

The order is unspecified. Compilers may choose any order, though all arguments are evaluated before the function runs.

Is f(i, i++) valid C?

No. It reads and modifies i without ordering, which is undefined behavior.

Why do different compilers print different results?

Because the standard leaves the order open, each compiler picks what suits its code generator.

How do I make the order predictable?

Evaluate each expression in its own statement, store the results in variables, then call the function.

Does the comma between arguments act as the comma operator?

No. It is only a separator, so it does not impose any order.

Does this free C tutorial cover interview topics?

Yes. This is a favorite embedded interview question, and the final lecture of the chapter collects more.

Write Predictable Embedded C

Keep following our free embedded C course and write firmware that behaves the same everywhere.

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

3 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 →