0

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?

6
  • 3
    You should up your compiler's warning level: ideone.com/3DQN40 Commented Jun 25, 2014 at 15:52
  • 3
    There's no "expected output" on undefined behavior. Commented Jun 25, 2014 at 15:53
  • I used gcc -Wall which indeed gave me a warning, but I'm curious why this behavior occurs Commented Jun 25, 2014 at 15:54
  • 2
    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. Commented Jun 25, 2014 at 15:54
  • 1
    See what a is before and after the call. Probably the same. Commented Jun 25, 2014 at 15:55

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

TIL printf returns a value.
I can't understand why there is 4 in the AX register. Is that a case or it can be recreate by others?
@neo_blackcap: printf has a return value. printf is documented that "On success, the total number of characters written is returned.". So it returns that it printed 4 characters successfully.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.