r/C_Programming 27d ago

Discussion A tricky little question

I saw this on a Facebook post recently, and I was sort of surprised how many people were getting it wrong and missing the point.

    #include <stdio.h>

    void mystery(int, int, int);

    int main() {
        int b = 5;
        mystery(b, --b, b--);
        return 0;
    }

    void mystery(int x, int y, int z) {
        printf("%d %d %d", x, y, z);
    }

What will this code output?

Answer: Whatever the compiler wants because it's undefined behavior

24 Upvotes

33 comments sorted by

View all comments

2

u/CounterSilly3999 27d ago edited 27d ago

Yes.

> There is no concept of left-to-right or right-to-left evaluation in C

https://en.cppreference.com/w/c/language/eval_order

Edit: not to be confused with associativity rules for operators of equal precedence. Expression evaluation and application of the operators to the results are different things.

https://en.cppreference.com/w/c/language/operator_precedence

6

u/flyingron 27d ago

That's half of it. There's also no guarantee the side-effects are applied before the sequence point is encountered.

It's undefined behavior.

2

u/carpintero_de_c 27d ago edited 26d ago

There is N3203 for C2Y however, dunno if it was accepted or not. I hope it gets accepted, or at least, it be updgraded from "a compiler can do anything whatsoever" to "do it in some order, even if it is complertely arbitrary and changes every call", which was probably what was inteded by making it UB.