Explanation behind value returned by int x=printf

Viewed 32

I was randomly experimenting with code and tried to assign printf to an integer variable, using different compilers. Different values were returned. What is the explanation for that?

#include <stdio.h>

int main ()
{
  int x;
  x = printf;
  printf ("%d", x);
  return 0;
}

Value returned on my compiler is 4195360.

1 Answers

Look at the warnings from your compiler. (If your compiler doesn't show a warning for this code, look up how to configure it to show useful warnings.)

a.c:5:5: warning: incompatible pointer to integer conversion assigning to 'int'
      from 'int (const char *, ...)' [-Wint-conversion]
  x = printf;
    ^ ~~~~~~
1 warning generated.

printf is a function. Every function can be used as a pointer to that function. A pointer to a function is a way to refer to the function that can be placed into a variable. Typically, it's the address of the code of the function in memory.

It's possible to assign a pointer to an integer. The resulting value depends on your system. The integer is typically the address of the code of the function in memory.

There's nothing useful you can do with this value except in some very particular circumstances (such as crafting binary exploits, or managing dynamic code loading). Anything you can do with the value would be very specific to a particular hardware and software environment.

Related