Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of printf()

Tags:

c

printf

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

like image 263
user3202188 Avatar asked Jan 22 '14 18:01

user3202188


People also ask

What is the function of printf ()?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

What is printf with example?

Example 1: C Output The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations. To use printf() in our program, we need to include stdio.h header file using the #include <stdio.h> statement.

What does %% mean in printf?

% indicates a format escape sequence used for formatting the variables passed to printf() . So you have to escape it to print the % character.


1 Answers

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

like image 61
abligh Avatar answered Sep 27 '22 21:09

abligh