ashu ashu - 2 months ago 5x
C Question

How does assigning a string to int and passing that int to printf prints the string properly?

Why does this work? (i.e how is passing

results in printing the string)


int main() {
int n="String";
return 0;

warning: initialization makes integer from pointer without a cast [enabled by default]

int n="String";

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]



compiler:gcc 4.8.5


In your code,

  int n="String";  //conversion of pointer to integer

is highly-implementation dependent note 1


 printf("%s",n);   //passing incompatible type of argument

invokes undefined behavior. note 2 Don't do that.

Moral of the story: The warnings are there for a reason, pay heed to them.

Note 1:

Quoting C11, chapter §

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. [....]

Note 2:

chapter §

[....] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

and for the type of argument for %s format specifier with printf()

s If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. [...]