• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variation in printf statement

 
aaka jain
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
main()
{
printf(3+ "proskills "+4);
}


can anyone tell me how this printf statement works in detail ,i am getting output as ls ,please explain how this statement is evaluated thanks
 
Mike Blaszczak
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
aaka jain wrote:
main()
{
printf(3+ "proskills "+4);
}


can anyone tell me how this printf statement works in detail ,i am getting output as ls ,please explain how this statement is evaluated thanks





A string literal in C or C++ is really just a pointer that's intialized to the string provided as the string literal. In other words, your program:



is equivalent to this one:



Once we know that the string is really just a pointer, we're enabled to understand how the addition operator applies to it. The string literal, being a pointer to characters, is just an address. When we add an integer n to a pointer, we create a new pointer that's at an address n elements adhead of the pointer. Characters are single bytes in these languages, so we move 3 characters forward in the string because we added 3. Then, we add 4 more to that pointer, so we move a total of 7 characters into the string.

Really, we're just looking into the string as if it was an array of characters:



We skip to the 7th character in the string (the second ell), get the address of that character, and pass it along to printf(). printf() prints the character it finds there, then moves to the next character and prints that one too, until it encounters a character that is the nul termination byte; '\0'. The nul terminator appears after the "s" at the end of the string, implicitly placed there by the language.

Hope that helps!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic