In <58**************************@posting.google.com >
ja*********@yahoo.com (Tushar) writes:
i would like to know why this code compiles and gives the output
Code 1:
----------
int main(){
printf("String" + 2);
}
Hard to answer, since this code invokes undefined behaviour, by calling
printf without a proper declaration in scope. Furthermore, due to the
missing newline character after the last line of output, it need not
produce any output at all.
Output: ring
Code 2:
----------
int main(){
printf("String", +2);
}
The same comments as above.
Output: String
I'll fix the first example and comment on it. The second one is so
easy that, if you can't figure out the answer by yourself, you should
stop messing with C.
#include <stdio.h>
int main()
{
printf("String\n" + 2);
return 0; /* main is a function returning int, right? */
}
A string literal appearing in a normal expression (other than as the
argument of sizeof) is replaced by a pointer to its first char, 'S' in
our case. You're adding 2 to this pointer, obtaining a pointer pointing
2 char's past 'S', i.e. to 'r'. This pointer is passed to printf as its
argument, which interprets it as its format string and behaves
accordingly. In other words, your printf call is equivalent to
printf("ring\n"), which explains the observed behaviour.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de