Reputation: 151
#include <stdio.h>
int main()
{
printf(5 + "Good Morning\n");
return 0;
}
The code prints Morning. Should the code print Morning or should it show undefined behavior?
Upvotes: 5
Views: 308
Reputation: 7442
The code is correct since printf
is defined as:
int printf ( const char * format, ... );
And according to pointers arithmitic 5 + "Good Morning\n"
is a pointer to the first element of "Morning\n"
. So the statment:
printf(5 + "Good Morning\n");
has the same result as:
printf("Morning\n");
Explanation:
|G|o|o|d| |M|o|r|n|i|n|g|\n|
^ ^
| |
"Good Morning\n" >---- |
+ |
5 >----------------------
Upvotes: 6
Reputation: 25189
It should show 'Morning'.
You are using pointer arithmetic - though you appear not to know it! "Good Morning\n"
is a char *
pointer to a constant string. You are then adding 5 to this pointer, which advances it by 5 characters. Hence the pointer now points to the 'M' of 'Morning'.
Upvotes: 11