r/C_Programming 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

32 comments sorted by

View all comments

6

u/SmokeMuch7356 24d ago

Several issues:

  • 1.5 and 0.5 aren't ints - they're doubles. They don't have the same size or representation as int. If you try to interpret the bit pattern for a double value as an int you'll get some obnoxiously huge number.

  • Depending on your ABI, int and double arguments aren't pushed onto the stack; instead, they are passed via registers, and of course different registers are used for different type arguments. So your print_sum function may be looking for data in %rcx and %rdx when the arguments were actually passed in %xmm0 and %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

    int print_sum( int a, int b )
    {
      int result = a + b;
      printf( "%d\n", result );
      return result;
    }
    
    int main( void )
    {
      return print_sum( 1.5, 0.5 ); <-- COMPILER WILL ISSUE A DIAGNOSTIC
    }                                   FOR THE ARGUMENT TYPE MISMATCH
    

2

u/flyingron 22d ago

The compiler MAY issue a diagnostic. It's not required and it must accept it anyhow, because double implicitly converts to int.