What will be the output of following 4 lines of codes? const char* p =…
What will be the output of following 4 lines of codes?
const char* p = "Hello";
printf("%c ", *p);
printf("%c ", *++p);
printf("%c ", *p++);
printf("%c ", *p);
Answer: A. H e e l — Explanation: const char* p = "Hello"; printf ("%c ", *p);// note space in format string printf ("%c ", *++p); // value of ++p is p after the increment printf…
- A.
H e e l
- B.
H e l l
- C.
H e l o
- D.
H H e l
Attempted by 202 students.
Show answer & explanation
Correct answer: A
Explanation:
const char* p = "Hello";
printf ("%c ", *p);// note space in format string
printf ("%c ", *++p); // value of ++p is p after the increment
printf ("%c ", *p++); // value of p++ is p before the increment
printf ("%c ", *p);// value of p has been incremented as a side effect of p++
Program declares p as a pointer to char. When we say "pointer to a char", what does that mean? It means that the value of p is the address of a char; p tells us where in memory there is some space set aside to hold a char.
The statement also initializes p to point to the first character in the string literal "Hello". For the sake of this exercise, it's important to understand p as pointing not to the entire string, but only to the first character, 'H'. After all, p is a pointer to one char, not to the entire string. The value of p is the address of the 'H' in "Hello".
const char* p = "Hello";
printf ("%c ", *p);// prints value pointed by pointer p i.e. H
printf ("%c ", ++p); // preincrement and has same precedence and ++ and * are right to left associative, hence value of ++p is p after the increment
printf ("%c ", p++); // postincrement has higher precedence than . But, the value of p++ is the value of p before the increment. So *p++, will be value before increment i.e. 'e'.
// After execution of above statement the value will be incremented now and p will be pointing to index location of l.
printf ("%c ", *p);// The current pointer value pointed by p is l.