Why am I getting this unexpected printf output?

I tried to understand how it printf

works in these cases: (this is a bonus question from the test)

Case 1:

int d=1;
printf("%d",(int)"printf("%d);

      

Output: 0

Case 2: (no end %d

at the end)

int d=1;
printf("%d",(int)"printf(");

      

Output: 15554368

How it works? And why %d

makes it different?

+3


source to share


3 answers


This bonus question is a trick:

printf("%d",(int)"printf("%d);

analyzed as

printf(
       "%d",
       ((int)"printf(") % d
      );

      

The string address is "printf("

converted to int

and the unit operation is calculated. Since d = 1

, the module is always 0

. Hence it printf

outputs 0

.

The second call just prints the address of the string converted to int

, what will differ from one environment to the next may even vary from one run to the next (this happens on my Mac) ...



In fact, the conversion may even fail and cause implementation specific behavior. So, in fact, the answer should be the implementation of certain behavior in both cases.

Another question should have been:

int d=1;
printf("%d",(int)printf("%d", d));

      

Creates 11

. Can you explain why?

Note that even this last question is tricky: a call printf

without a proper prototype, for example, if <stdio.h>

not included, has undefined behavior.

+3


source


Let's start with the second example:

int d=1;
printf("%d",(int)"printf(");

      

"printf("

Here's a string constant containing just the name of the C function to confuse you. A string constant has a type char *

, it is a pointer to the first character. (int)

converts a pointer to an integer. Although this implementation is defined, you will get some value that is associated with the address where the string is actually stored "printf("

.

So you are printing a number here, which is the result of converting a pointer to int

.



Moving:

int d=1;
printf("%d",(int)"printf(" % d);

      

There is only one change, and I added spaces to make it obvious: int

what you get from a pointer conversion is modulo d

, so the result is the remainder of an integer division by d

. Since it d

is one, there will never be any remainder, any number is divisible by 1 without a remainder. Therefore the result 0

.

+3


source


The second is %d

not a specifier printf()

, it's a modular division operator %

and a variable int

d

that matters 1

, what's the difference? they are not alike at all.

The second problem is that you are casting a pointer to int

that is not defined.

+2


source







All Articles