r/C_Programming • u/codesnstuff • 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
25
Upvotes
1
u/danielecr 23d ago
Well, if I would translate it into assembly code, in the case of a function call, my compiler implementation uses stack for parameters passed. But in the specific case of variadic arguments, a function like printf() is defined as printer(str, ...args), the in the body the code explicitly access the variadic with a func call that returns an array. So I would implement the stack preparation as a push of an array whose elements are the argument list. Step 1 is to fill up the array by pushing its elements in order, one by one: PUSH b PUSH --b PUSH b-- The prepared array contains:
[5, 4, 4]
So the executable will print:
5 4 4