Examveda

What will be the output of the following C code?
#include <stdio.h>
int x;
void main()
{
    if (x)
        printf("hi");
    else
        printf("how are u");
}

A. hi

B. how are you

C. compile time error

D. error

Answer: Option B

Solution (By Examveda Team)

#include <stdio.h>: This line includes the standard input/output library, which is needed for the printf function.
int x;: This declares an integer variable named x. Crucially, x is declared globally but *not* initialized. This means it will have a default value.
void main(): This is the main function where the program execution begins.
if (x): This is the core of the question. The if statement checks the value of x. In C, any non-zero value is treated as true, and zero is treated as false.
printf("hi");: This line will be executed if the condition x is true.
else printf("how are u");: This line will be executed if the condition x is false.

Now, the key point is that since x is a global variable and is not explicitly initialized, it's automatically initialized to 0 by the C compiler.
Therefore, the condition if (x) is equivalent to if (0), which is false.
So, the else block will be executed, and the program will print "how are u".

Therefore, the correct answer is Option B: how are you

This Question Belongs to C Program >> Control Structures

Join The Discussion

Comments (1)

  1. Tawana Kapofu
    Tawana Kapofu:
    4 months ago

    x is a global variable, and in C, global variables are implicitly initialized to 0.
    The condition if (x) checks if x is non-zero (true). Since x == 0, it's false.
    So the else block executes.

Related Questions on Control Structures