Pages

3 Essential C Interview Questions



1.What will be the output when the following code is executed? Explain.
#include <stdio.h>
#define SQUARE(a) (a)*(a)

int main() {
    printf("%d\n", SQUARE(4));
    int x = 3;
    printf("%d\n", SQUARE(++x));
}


Answer:

The answer is infact undefined, and depends on the compiler being used. Some compilers will result in 16 and 20, while others will produce 16 and 25.
One might expect the second use of the SQUARE macro to yield 16, just like the first use of the SQUARE macro. However, macros are processed by the preprocessor, a step that takes place before actual compilation begins. Expanding the second macro will show what actually gets compiled:
(++x)*(++x)
The evaluation of the pre-increment operation ++x is where the undefined behavior in C comes in. With some compilers, the macro will reduce to (4)*(5), while in other cases, it will be evaluated as (5)*(5).
This article discusses this behavior further.


2.Why is it usually a bad idea to use gets()? Suggest a workaround?

Answer:

The function gets() reads characters from the stdin and stores them at the provided input buffer. However, gets() will keep reading until it encounters a newline character. Unless the buffer is large enough, or the length of the line being read is known ahead of time, gets() can potentially overflow the input buffer and start overwriting memory it is not supposed to, wreaking havoc or opening security vulnerabilities.
One way to work around this issue is to use fgets(). It allows you to put a limit on the maximum number of characters to read:
fgets(b, 124, stdin);

3.What is the difference between structs and unions?

Answer:

A struct is a complex data type that allows multiple variables to be stored in a group at a named block of memory. Each member variable of a struct can store different data, and they all can be used at once.
struct a {
    int x;
    char y;
} a;
For example, you may store an integer in x, and and a character in y above, independent of each other.
A union, on the other hand, stores the contents of any member variable at the exact same memory location. This allows the storage of different types of data at the same memory location. The result is that assigning a value to one member will change the value of all the other members. Unlike struct, only one member of the union type is likely to be useful at any given time.
union b {
    int x;
    char y;
} b;
For example, storing a character in y may automatically change the integer you read from x to something meaningless or unpredictable.

Nithin

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment