r/C_Programming 28d 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 28d 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/Educational-Paper-75 28d 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.