hi,
i saw this code somewhere but did not get the concept behind it.why the output is nothing?
Code:#include<stdio.h> int main(void) { printf(5+"good"); }
hi,
i saw this code somewhere but did not get the concept behind it.why the output is nothing?
Code:#include<stdio.h> int main(void) { printf(5+"good"); }
"good" is an array of five characters with value 'g', 'o', 'o', 'd', and '\0' (also referred to as terminating zero).
The expression 5+"good" treats the array "good" as if it is a pointer to char, with the value equal to the address of the letter 'g'. 5+"good" is therefore equal to the address of a char 5 past the letter 'g' (i.e. one past the end of the array).
printf() therefore receives a pointer to a char which contains the address of a character one past the terminating zero.
The problem with your example is that it is not guaranteed to produce nothing. There is no guarantee that a char exists which is one past the terminating zero. Your code therefore exhibits undefined behaviour. That means any result your program produces is valid. It might print horses. It might print nothing. It might reformat your hard drive and try to download and install windows 8.1 to it. Any result is acceptable because the code exhibits undefined behaviour.
If the statement has been printf(2 + "good"), then printf() would have started printing at the second 'o', and kept going until it encountered the terminating zero. So it would have printed "od" (without the quotes). If the statement had been printf(4 + "good") printf() would have immediately encountered the terminating zero and returned, so it would print nothing.