1. What is output of below code snippet ?
#include <stdio.h>struct Node {
int a;
int b;
};
int main() {
struct Node *p = NULL;
if (p && p->a) {
p->a = 2;
printf("%p, %d\n", (void*)p, p->a);
}
printf("reached outside\n");
return 0;
}
Answer :- The program will print "reached outside" because the condition p && p->a evaluates to false due to p being NULL. The statement inside the if-block will not be executed, and the program will continue to the next statement after the if-block.
Now, let's analyze the code behavior:
struct Node *p = NULL; A pointer p to the struct Node is declared and initialized to NULL.
if (p && p->a): The condition checks if p is not NULL (p &&) and then attempts to access the member a of the structure using the arrow operator (p->a). However, since p is NULL, dereferencing it (p->a) will result in undefined behavior. The condition will evaluate to false.
The program will not enter the if-block, and the statement printf("reached outside\n"); will be executed.