Reputation: 6753
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 .
Upvotes: 1
Views: 6163
Reputation: 31637
"%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
.
Upvotes: 6
Reputation: 9321
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
Upvotes: 4