#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?
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 >---------------------- printf, backtracked to bytes prior to the pointer passed - as well as the fact it wastes space in normal circumstances.
printf("%s", "Good Morning\n" + 5)instead