I am not able to understand the output of the following C code :
#include
main()
{
char * something = \"something\";
printf(\"%c\", *someth
always use the clockwise rule clockwise rule
printf("%c\n", *something++);
according to the rule you will first encounter * so get the value then ++ means increment
in the 3rd case printf("%c\n", *something++);
so according to the image increment the value ++ and then get the value *
See http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence for details
printf("%c", *something++);
Gets the char at *something and then increments it ('s')
printf("%c", *something);
Just get the char (now the second, due to the increment in the last statement ('o')
printf("%c", *++something);
increment and then get the char of the new position ( 'm' )
printf("%c", *something++);
Gets the char at *something and then increments it ('m')
// main entrypoint
int main(int argc, char *argv[])
{
char * something = "something";
// increment the value of something one type-width (char), then
// return the previous value it pointed to, to be used as the
// input for printf.
// result: print 's', something now points to 'o'.
printf("%c", *something++);
// print the characer at the address contained in pointer something
// result: print 'o'
printf("%c", *something);
// increment the address value in pointer something by one type-width
// the type is char, so increase the address value by one byte. then
// print the character at the resulting address in pointer something.
// result: something now points at 'm', print 'm'
printf("%c", *++something);
// increment the value of something one type-width (char), then
// return the previous value it pointed to, to be used as the
// input for printf.
// result: print 's', something now points to 'o'.
printf("%c", *something++);
}
Result:
somm
It is pretty simple.
char * something = "something";
Assignment of pointer.
printf("%c\n", *something++);//equivalent to *(something++)
Pointer is incremented but the value before increment is dereferenced ans it is post-increment.
printf("%c\n", *something);//equivalent to *(something)
Pointer is now pointing to 'o' after increment in the previous statement.
printf("%c\n", *++something);//equivalent to *(++something)
Pointer is incremented to point to 'm' and dereferenced after incrementing the pointer as this is pre-increment.
printf("%c\n", *something++);//equivalent to *(something++)
Same as the first answer.
Also notice '\n'
at the end of every string in printf. It makes the output buffer flush and makes the line print. Always use a \n
at the end of your printf.
You may want to look at this question as well.