Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to understand the output of the program using printf weirdly

Tags:

c

printf

I was working 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;
}

It prints the following:

d

I am unable to understand how the printf function works here.

like image 946
user3126632 Avatar asked Sep 26 '14 16:09

user3126632


1 Answers

Let's look at the first argument to the printf() call.

"%d" + 1

This points to the same thing as ptr does in the following code.

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

So, what does it mean to increment a pointer? Well, we advance the pointer sizeof(*ptr) * 1 bytes 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 doing:

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

Which will evaluate and then ignore the extra function argument and print d.


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

You can find a full table of format strings here.

like image 165
Bill Lynch Avatar answered Oct 12 '22 11:10

Bill Lynch