Unable to understand program output with printf weirdly

I worked with some of the interview questions when I found this code.

#include<stdio.h> int main() { short int a=5; printf("%d"+1,a); //does not give compiler error return 0; } 

He prints the following:

 d 

I can’t understand how printf function works.

+8
c printf
source share
4 answers

Look at the first argument to printf() .

 "%d" + 1 

This indicates the same as ptr in the following code.

 char *ptr = "%d"; ptr = ptr + 1; 

So what does it mean to increment a pointer? So we move the sizeof(*ptr) * 1 bytes sizeof(*ptr) * 1 forward.

So, in memory we have:

 %d\0 ^^ || |This is where ("%d" + 1) points to. This is where ("%d") points to. 

So your code is more or less functionally equivalent to executing:

 short int a = 5; printf("d", a); 

What will be evaluated, then ignore the optional function argument and print d .


One more thing:. You are very close to undefined behavior in this code. printf("%d", a) uses the wrong format string. The correct format string for short int is "%hd" .

You can find the full format string table here .

+16
source share

"%d" + 1 performs pointer arithmetic, the compiler sees it as "d" , therefore

 printf("%d"+1,a); 

becomes:

 printf("d", a); 

You can understand why it outputs d to your compiler.

As @sharth notes in a comment, the optional argument a is evaluated and discarded here.

+7
source share

This is my answer based on @DCoder's comment. "%d" is the pointer to the first character of the %d character array. Incrementing this by one gives a pointer to d . The fact that there is now a second argument does not matter, because the result of the expression "%d"+1 is just the symbol d . If you try to add 0 , your output will be 5 , as expected. If you try to add 2 , there is no output, because only "" is passed to printf .

+2
source share

In this case, printf("%d"+1,a); = printf("d",a) .

You specify printf to print from position +1, which is "d" , so printf will just print d on the screen.

+1
source share

All Articles