void is used in two contexts: (1) as a function return type when a function doesn't return a value, and (2) to declare a generic pointer (void *) that can point to any data type.
What is the output of the following C code?
int a = 10, b = 20;
int c = (a > b) ? a : b;
printf("%d", c);
A10
B20
CCompilation error
D30
Correct Answer:
B. 20
Explanation:
The ternary operator (condition ? true_value : false_value) evaluates the condition (a > b). Since 10 is not greater than 20, it returns b which is 20.
What is the output of the following C code?
int x = 5;
int y = ++x + x++;
printf("%d", y);
A11
B12
C13
DUndefined behavior
Correct Answer:
D. Undefined behavior
Explanation:
This code exhibits undefined behavior because x is modified twice between sequence points without an intervening sequence point. The result depends on the compiler's implementation.
What is the difference between scanf() and gets() functions?
Ascanf() can read formatted input while gets() reads only strings
Bgets() is safer than scanf()
CThere is no difference
Dscanf() stops at whitespace while gets() doesn't
Correct Answer:
A. scanf() can read formatted input while gets() reads only strings
Explanation:
scanf() reads formatted input based on format specifiers and stops at whitespace. gets() reads a string until a newline is encountered. Note: gets() is deprecated due to buffer overflow vulnerabilities.
What is the correct way to allocate memory for a single integer using malloc()?
Aint *ptr = (int *)malloc(sizeof(int));
Bint *ptr = malloc(sizeof(int));
Cint *ptr = (int *)malloc(4);
DBoth A and B
Correct Answer:
D. Both A and B
Explanation:
Both A and B are correct. Option A uses explicit type casting which is optional in C (not in C++). Option B avoids casting. Using sizeof(int) is preferred over hardcoding 4, as int size may vary across systems.
What happens when you use the strcpy() function without bounds checking?
AIt prevents buffer overflow automatically
BIt may cause buffer overflow if source string is longer than destination
CIt returns an error code
DIt truncates the source string automatically
Correct Answer:
B. It may cause buffer overflow if source string is longer than destination
Explanation:
strcpy() does not perform bounds checking. If the source string is longer than the destination buffer, it will write beyond the buffer boundary, causing a buffer overflow. This is a security vulnerability. Using strncpy() is safer.