简体   繁体   中英

void function pointer return value in C

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM