Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C "%d" format specifier

The following code gives me the output as 'd':

void main()
{

  short int a=5;

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

   getch();

}

How does printf() actually work?

like image 483
poorvank Avatar asked Sep 27 '12 15:09

poorvank


2 Answers

printf does not "see" the format specifier because you are passing a pointer to "%d" plus one. This is equivalent to passing "d" by itself:

printf("d", a);

will print d and ignore a. This is not specific to printf, pointer arithmetic works like that with all char pointers, including pointers obtained from string literals (i.e. double-quoted sequences of characters).

like image 123
Sergey Kalinichenko Avatar answered Oct 13 '22 10:10

Sergey Kalinichenko


here is the problem printf("%d"+1,a); it wont display because there is only one format specifier and this ("%d"+1) generate error

it can be either printf("%d+1",a); or printf("%d",a+1);

like image 21
NullPoiиteя Avatar answered Oct 13 '22 09:10

NullPoiиteя