1

I would like to know what is happening in this simple c code:

#include <stdio.h>
int something(int a, int b) {
    int c = a * 3 + 4 * b;
}
int main()
{
    int res = something(12, 54);
    printf("%d\n", res);    
    return 0;
}

The function does not have the return, however "res" stores the value calculated in something.

Following I show the compilation command, the execution and the output:

$ gcc main.c

$ ./a.out

252


EDITED

I have changed the variables types from int to float, in relation to the @Paul Ogilvie comment, and it seems to return the last int stored:

#include <stdio.h>
float something(int a, int b) {
    float res = a * 3 + 4 * b * 1.0;
}
int main() {
    float res = something(12, 54);
    printf("%d\n", res);
    return 0;
}

$ gcc main.c

$ ./a.out

54

Bub Espinja
  • 4,029
  • 2
  • 29
  • 46
  • @Codor compiling with -Wall you get that warning. – Bub Espinja Feb 10 '17 at 15:19
  • According to the answer of Christoph Terasa, in my case, the undefined behaviour is the explained by @Paul Ogilvie. – Bub Espinja Feb 10 '17 at 15:38
  • For x86 at least, the return value of this function should be in eax register. Anything that was there will be considered to be the return value by the caller. Because eax is used as return register, it is often used as "scratch" register by callee, because it does not need to be preserved. This means that it's very possible that it will be used as any of local variables. Because both of them are equal at the end, it's more probable that the correct value will be left in eax. – Vishnu CS Mar 06 '20 at 06:39

1 Answers1

3

It is undefined behavior, see here:

Reaching the end of any other value-returning function is undefined behavior, but only if the result of the function is used in an expression.

Compiling your code with gcc -Wreturn-type gives the appropriate warning:

ret.c:4:1: warning: control reaches end of non-void function [-Wreturn-type]
Jan Christoph Terasa
  • 5,781
  • 24
  • 34