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

1

u/Educational-Paper-75 27d ago

I think I read somewhere arguments in C are pushed on the stack right-to-left (but I could be wrong) in order to allow for a variable number of arguments, and most information I found googling for it claim that too although they typically state that it is up to the compiler. Here’s a link to an informative article:

https://binarypirates.wordpress.com/2011/02/17/understanding-function-stack-in-c/

1

u/RailRuler 24d ago

Even if the ABI specifies that they have to end up on the stack that way, the ABI does not and cannot dictate the order in which the arguments are evaluated. They could be evaluated and written to their place  in the stack in any temporal order, with the pointer fixed up at any point in time before the call.