Predict the outputs of following C programs.
Question 1
int main()
{
int x = 10;
static int y = x;
if (x == y)
printf ( "Equal" );
else if (x > y)
printf ( "Greater" );
else
printf ( "Less" );
getchar ();
return 0;
}
|
Output: Compiler Error
In C, static variables can only be initialized using constant literals. See this GFact for details.
Question 2
#include <stdio.h>
int main()
{
int i;
for (i = 1; i != 10; i += 2)
{
printf ( " GeeksforGeeks " );
}
getchar ();
return 0;
}
|
Output: Infinite times GeeksforGeeks
The loop termination condition never becomes true and the loop prints GeeksforGeeks infinite times. In general, if a for or while statement uses a loop counter, then it is safer to use a relational operator (such as <) to terminate the loop than using an inequality operator (operator !=). See this for details.
Question 3
#include<stdio.h>
struct st
{
int x;
struct st next;
};
int main()
{
struct st temp;
temp.x = 10;
temp.next = temp;
printf ( "%d" , temp.next.x);
getchar ();
return 0;
}
|
Output: Compiler Error
A C structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!