Top C Interview Questions(2024)
Question: What is the difference between struct
and union
in C?
Answer:
In C, both struct
and union
are used to group different data types together under a single name, but they differ significantly in terms of memory allocation and usage. Here are the key differences between struct
and union
:
1. Memory Allocation:
-
struct
:- In a
struct
, all the members are allocated their own memory, and each member can hold a value simultaneously. The total size of the structure is the sum of the sizes of its members, and possibly some padding to align the data types according to memory alignment rules. - Each member has its own memory location, so they can store different values at the same time.
Example:
struct Example { int i; // 4 bytes char c; // 1 byte float f; // 4 bytes };
The total memory required for
struct Example
would be at least4 + 1 + 4 = 9 bytes
, but due to padding (for alignment), it might be larger (e.g., 12 bytes on some systems). - In a
-
union
:- In a
union
, all members share the same memory location. Only one member can hold a value at any given time. The memory size of the union is the size of its largest member. The total size of the union is the size of its largest member (not the sum of the sizes of all members). - Since all members share the same memory, a union can only store one of its members’ values at a time. When you assign a value to one member, the value of the other members will be overwritten.
Example:
union Example { int i; // 4 bytes char c; // 1 byte float f; // 4 bytes };
The total memory required for
union Example
would be the size of the largest member, which is4 bytes
(sinceint
andfloat
typically take 4 bytes). Thus, it will take 4 bytes of memory regardless of the number of members. - In a
2. Usage:
-
struct
:- A
struct
is used when you need to store different data types and want all of them to hold values simultaneously. It is ideal when you want to represent an entity or object that has multiple attributes that should all be stored together (e.g., aPerson
withname
,age
, andsalary
).
Example:
struct Person { char name[50]; int age; float salary; };
- A
-
union
:- A
union
is used when you need to store different types of data, but only one of them needs to be stored at a time. It is ideal when you want to save memory and are only interested in storing one of the possible values (e.g., storing an integer, float, or character in a variable, but not more than one at a time).
Example:
union Data { int i; float f; char c; };
- A
3. Access to Members:
-
struct
:- In a
struct
, all members can be accessed independently. You can modify and use the values of all members at the same time.
Example:
struct Person p1; p1.age = 25; p1.salary = 50000.50; strcpy(p1.name, "John Doe");
- In a
-
union
:- In a
union
, you can only access the most recently assigned member, and all other members will contain garbage or the last assigned value. This is because they all share the same memory location.
Example:
union Data data; data.i = 10; // Assigning value to int printf("%d\n", data.i); // Prints 10 data.f = 3.14; // Assigning value to float (overwrites int) printf("%f\n", data.f); // Prints 3.14 printf("%d\n", data.i); // Prints garbage or the last assigned value
- In a
4. Memory Efficiency:
-
struct
:struct
consumes more memory because each member has its own separate memory allocation.- If you have a large number of members, the memory consumption can add up quickly.
-
union
:union
is more memory efficient because it only needs enough memory for the largest member. However, you can only use one member at a time.
5. Size of Structure vs Union:
struct
: The size of astruct
is the sum of the sizes of its individual members, plus any padding added by the compiler for alignment.union
: The size of aunion
is the size of its largest member.
6. Example of struct
and union
:
#include <stdio.h>
struct ExampleStruct {
int i; // 4 bytes
char c; // 1 byte
float f; // 4 bytes
};
union ExampleUnion {
int i; // 4 bytes
char c; // 1 byte
float f; // 4 bytes
};
int main() {
struct ExampleStruct structVar;
union ExampleUnion unionVar;
// Assign values to struct members
structVar.i = 10;
structVar.c = 'A';
structVar.f = 3.14;
printf("Struct Example:\n");
printf("i: %d, c: %c, f: %.2f\n", structVar.i, structVar.c, structVar.f);
printf("Size of struct: %lu bytes\n\n", sizeof(struct ExampleStruct));
// Assign values to union members
unionVar.i = 10;
printf("Union Example (after assigning to i):\n");
printf("i: %d\n", unionVar.i);
unionVar.c = 'A';
printf("Union Example (after assigning to c):\n");
printf("c: %c\n", unionVar.c);
printf("Size of union: %lu bytes\n", sizeof(union ExampleUnion));
return 0;
}
Output:
Struct Example:
i: 10, c: A, f: 3.14
Size of struct: 12 bytes
Union Example (after assigning to i):
i: 10
Union Example (after assigning to c):
c: A
Size of union: 4 bytes
7. Key Differences Summary:
Feature | struct | union |
---|---|---|
Memory Allocation | Each member gets its own memory | All members share the same memory |
Size | Size = sum of sizes of all members + padding | Size = size of largest member |
Access | All members can be accessed at once | Only the most recently assigned member can be accessed |
Use Case | Storing different data that needs to be accessed simultaneously | Storing different types of data, but only one at a time |
Memory Efficiency | Less memory-efficient | More memory-efficient |
Conclusion:
-
Use
struct
when you need to store multiple types of data and access all the members simultaneously. Structures are ideal for representing complex objects or records where each field needs to hold a separate value. -
Use
union
when you need to store different types of data in the same memory space, but only one value at a time. Unions save memory but limit the ability to store multiple values at once.
Question: What are the different types of loops in C?
Answer:
In C, loops are used to execute a block of code repeatedly based on certain conditions. There are three main types of loops:
1. for
Loop:
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
- Initialization: Executed once at the beginning. It typically defines and initializes the loop counter variable.
- Condition: Checked before each iteration. If the condition evaluates to
true
, the loop continues. If it’sfalse
, the loop stops. - Increment/Decrement: Executed after each iteration. It typically updates the loop counter.
Example:
#include <stdio.h>
int main() {
// Print numbers from 1 to 5 using a for loop
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
4
5
2. while
Loop:
The while
loop is used when you want to repeat a block of code an unknown number of times, but you have a condition that must be met for the loop to run. The condition is evaluated before each iteration.
Syntax:
while (condition) {
// Code to be executed
}
- Condition: Checked before each iteration. The loop continues to execute as long as the condition evaluates to
true
.
Example:
#include <stdio.h>
int main() {
int i = 1;
// Print numbers from 1 to 5 using a while loop
while (i <= 5) {
printf("%d\n", i);
i++; // Increment i
}
return 0;
}
Output:
1
2
3
4
5
3. do-while
Loop:
The do-while
loop is similar to the while
loop, but the condition is evaluated after the loop’s body has executed. This ensures that the code inside the loop is executed at least once, even if the condition is false
initially.
Syntax:
do {
// Code to be executed
} while (condition);
- Condition: Checked after each iteration. The loop will always execute the code block at least once.
Example:
#include <stdio.h>
int main() {
int i = 1;
// Print numbers from 1 to 5 using a do-while loop
do {
printf("%d\n", i);
i++; // Increment i
} while (i <= 5);
return 0;
}
Output:
1
2
3
4
5
Comparison of Loops:
Feature | for loop | while loop | do-while loop |
---|---|---|---|
Condition Check | Before each iteration | Before each iteration | After each iteration |
Execution | Executes a fixed number of times | Executes as long as the condition is true | Executes at least once, even if the condition is false |
Usage | When the number of iterations is known | When the number of iterations is not known | When you need to execute the loop body at least once |
Syntax | for (initialization; condition; increment/decrement) | while (condition) | do { } while (condition); |
4. Nested Loops:
In addition to these basic loops, you can use loops inside other loops, which are called nested loops. They are often used when working with multi-dimensional arrays or solving complex problems like matrix manipulations.
Example:
#include <stdio.h>
int main() {
// Print a 3x3 matrix using nested for loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
return 0;
}
Output:
1 2 3
2 4 6
3 6 9
5. break
and continue
Statements:
-
break
: Used to exit a loop prematurely, regardless of the loop’s condition.Example:
for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit the loop when i equals 5 } printf("%d ", i); } // Output: 1 2 3 4
-
continue
: Used to skip the current iteration of a loop and move to the next iteration.Example:
for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip the iteration when i equals 3 } printf("%d ", i); } // Output: 1 2 4 5
Conclusion:
- The
for
loop is useful when you know the number of iterations in advance. - The
while
loop is best when the number of iterations is unknown, and the loop needs to continue as long as a condition is true. - The
do-while
loop ensures that the loop body is executed at least once, making it suitable for scenarios where you need the loop to run regardless of the condition.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as C interview questions, C interview experiences, and details about various C job positions. Click here to check it out.
Tags
- C Language
- Pointers
- Memory Management
- Data Types
- Structures
- Unions
- Functions
- Function Pointers
- Static Keyword
- C Programming
- C Arrays
- Loops in C
- Memory Allocation
- Malloc
- Calloc
- Segmentation Fault
- Error Handling in C
- Header Files
- Macros in C
- String Handling
- Const Keyword
- C Interview Questions
- C++ vs C
- Pre increment
- Post increment
- C Syntax
- C Debugging
- C Programming Concepts
- Manual Memory Management
- Exit vs exit
- C Programming Techniques