needed explanation for a c-program
In a c-book 开发者_如何学JAVAI bought, an exercise program is given as
what is the output for the following code snippet?
printf(3+"Welcome"+2);
the answer I got is me (by executing it in TC++)
But I can't get the actual mechanism. please explain me the actual mechanism behind it.
It's called pointer arithmetic: 2+3=5, and "me" is the rest of the string starting at offset 5.
PS: throw away that book.
When this is compiled the "Welcome" string becomes a const char *
, pointing to the first character of the string. In C, with character strings (like any pointer), you can do pointer arithmetic. This means pointer + 5 points to 5 places beyond pointer.
Therefore ("Welcome" + 5) will point 5 characters past the "W", to the substring "me."
On a side note, as other have suggested, this doesn't sound like a good book.
A string (like "Welcome"
) is an array of characters terminated by the NUL-character (so it's actually "Welcome\0"
).
What you are doing, is accessing the fifth character of it (3 + 2 = 5). This character is 'm'
(array indices start at 0).
printf
will continue to read till it hits the NUL-character.
精彩评论