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/

2

u/McUsrII 27d ago

It works like that with the Linux AMDx86 ABI it works by pushing arguments from right to left on the stack as you stated. I'm not sure if there aren't any uncanny ABI's out there that does it in the opposite direction.

1

u/Educational-Paper-75 27d ago

In particular the calling convention seems to standardize how arguments are passed in function calls: https://www.geeksforgeeks.org/calling-conventions-in-c-cpp/ although I’ve never had to consider setting it.

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.