aspose file tools*
The moose likes C / C++ and the fly likes variation in printf statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "variation in printf statement" Watch "variation in printf statement" New topic
Author

variation in printf statement

aaka jain
Greenhorn

Joined: May 16, 2013
Posts: 12
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

Joined: Sep 02, 2013
Posts: 22
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!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: variation in printf statement