ExamVeda
Login
Home
This question belongs to C Program Control Structures
Control Structures
?

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");
}

Answer & Solution
Correct Answer: Option B
#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
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Tawana Kapofu
Tawana Kapofu 1 year 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.