C Programming - Const - Discussion

Discussion Forum : Const - Find Output of Program (Q.No. 6)
6.
What will be the output of the program?
#include<stdio.h>

int main()
{
    const char *s = "";
    char str[] = "Hello";
    s = str;
    while(*s)
        printf("%c", *s++);

    return 0;
}
Error
H
Hello
Hel
Answer: Option
Explanation:

Step 1: const char *s = ""; The constant variable s is declared as an pointer to an array of characters type and initialized with an empty string.

Step 2: char str[] = "Hello"; The variable str is declared as an array of charactrers type and initialized with a string "Hello".

Step 3: s = str; The value of the variable str is assigned to the variable s. Therefore str contains the text "Hello".

Step 4: while(*s){ printf("%c", *s++); } Here the while loop got executed untill the value of the variable s is available and it prints the each character of the variable s.

Hence the output of the program is "Hello".

Discussion:
23 comments Page 3 of 3.

Madhu said:   1 decade ago
Here *s is a constant pointer how can it's value be changed from 'NULL' to 'str' .

Mohini said:   1 decade ago
while(*s)
this condition says that while loop will get executed till there is no NULL,i.e end of string.
so it will go on printing each character till the end of string.
thus whole string gets printed

Ckbrave13 said:   2 decades ago
Here 'str' points to location of 'H'.When s = str ,'s' contains location of 'H'.'*s' points to 'H' and each time it increments it prints "HELLO".


Post your comments here:

Your comments will be displayed after verification.