0
votes

I was playing around with function pointers in C just to learn. I tried calling a void function and setting its result to an int.

void function(int x, int y){
printf("%d,%d\n",x,y);
}

int main(){
    int (*fptr)(int,int);
    fptr = function;
    int a = fptr(2,3);
    printf("%d\n",a);
    return 0;
}

The output I get from this is:

2,3 4

After playing around with this a little, I realized that main is printing the number of characters in the printf statement in function(). Why is this happening? Is this expected output?

2
You should up your compiler's warning level: ideone.com/3DQN40 - Oliver Charlesworth
There's no "expected output" on undefined behavior. - Happington
I used gcc -Wall which indeed gave me a warning, but I'm curious why this behavior occurs - samGbos
You could get anything. Random. It might just happen to provide the return of the printf since that's what's left in the accumulator when the function returns (printf was the last thing called and it does have a return value). But it's not guaranteed. You can't count on it. So is it expected? No. Is it explainable? Yes. - lurker
See what a is before and after the call. Probably the same. - Fiddling Bits

2 Answers

7
votes

This is undefined behavior, and therefore, any behavior at all is "in spec", including "Nasal Demons"

However, we can explain why this is likely happening on many modern platforms.

The return value of the last function that has a return value is usually placed in the AX register of the CPU.

printf was the last function that had a return value, and put 4 into the AX register.
Nothing else over-wrote the AX register in the meantime, and variable a gets the "return value" (even though fptr does not have a return value!), by getting the contents of the AX register, which is still 4.

0
votes

This is expected result! The printf() function will return the number of characters printed.In this case,fptr(2,3) will print 2,3 AND \n, therefor it return 4