cstringintprintf

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 int to printf() results in printing the string)

#include<stdio.h>

int main() {
    int n="String";
    printf("%s",n);
    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=]
printf("%s",n);

Output:String

compiler:gcc 4.8.5


Solution

  • In your code,

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

    is highly-implementation dependent note 1

    and

     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 §6.3.2.3

    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 §7.21.6.1

    [....] 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. [...]