5
#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?

3
  • What made you to include "undefined behavior" as a possible scenario? What specifically made you suspect UB in this code? Commented Jan 22, 2014 at 18:35
  • 1
    The answers here already do a good job explaining what is going on but as a rule of thumb, you should avoid having a non-constant format parameter for printf since that makes it harder for the compiler to find type errors. Consider doing printf("%s", "Good Morning\n" + 5) instead Commented Jan 22, 2014 at 19:14
  • Odd to find that this isn't a dup of numerous questions. Pointer arithmetic seems rare. Commented Jan 22, 2014 at 20:16

2 Answers 2

11

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'.

Sign up to request clarification or add additional context in comments.

Comments

6

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 >---------------------- 

1 Comment

It's not entirely equivalent as the binary will still contain the whole string. This might be significant if the function, unlike printf, backtracked to bytes prior to the pointer passed - as well as the fact it wastes space in normal circumstances.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.