1

I'm learning C language and stuck with a question as follows:

#include<stdio.h>
#include<conio.h>
void main()
{
short int a=5;
clrscr();
printf("%d"+1,a);
getch();
}

Please explain what is the output of this program. Thanks .

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84

2 Answers2

6

"%d" is a const char* that points to the first character of "%d".

"%d" + 1 is a const char* that points to the second character of "%d" (i.e. the string "d").

Passing "d" as format to printf prints d, regardless of what additional arguments you pass to printf.

Oswald
  • 31,254
  • 3
  • 43
  • 68
4

Let's see it another way:

#include<stdio.h>
#include<conio.h>
void main()
{
short int a=5;
clrscr();
char const * string = "%d";
char const * newString = string + 1;
printf(newString,a);
getch();
}

The output is 'd', since 'string' is a pointer, which points to the address of the '%'. If you increment this pointer by one, to get 'newString', it'll point to the character 'd'. That's why the output is 'd', and printf basically discards its second argument.

The memory layout is the following (note the terminating zero char '\0'):

[%] [d] [\0]
 ^   ^
 |   |
 |   newString
string
Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46