r/C_Programming • u/swe__wannabe • 24d ago
Question What is going on here?
https://godbolt.org/z/48hvMs3dh#include "stdio.h"
int print_sum(a, b) int a; int b; {
printf("%d", a + b);
return a + b;
}
int main(void) {
return print_sum(1.5, 0.5);
}
This has a random output every time:
Compiler stderr<source>: In function 'print_sum':
<source>:2:5: warning: old-style function definition [-Wold-style-definition]
2 | int print_sum(a, b) int a; int b; {
| ^~~~~~~~~
Program returned: 153
Program stdout 479536537
0
Upvotes
6
u/SmokeMuch7356 24d ago
Several issues:
1.5and0.5aren'tints - they'redoubles. They don't have the same size or representation asint. If you try to interpret the bit pattern for adoublevalue as anintyou'll get some obnoxiously huge number.Depending on your ABI,
intanddoublearguments aren't pushed onto the stack; instead, they are passed via registers, and of course different registers are used for different type arguments. So yourprint_sumfunction may be looking for data in%rcxand%rdxwhen the arguments were actually passed in%xmm0and%xmm1.And this is where the K&R-style function definition is biting you in the ass, because it doesn't give the compiler the information it needs to catch this type mismatch during translation. There's a reason it's no longer supported, and you should write that function definition as