A

Akash Lawaniya • 9.58K Points
Tutor III

Q. In the following C code, the union size is decided by?

Code:
union temp
    {
        char ch;
        int n;
        float f;
    };
  • (A) float
  • (B) int
  • (C) both float and int
  • (D) char

Explanation by: Mr. Dubey

The correct answer is:

(A) float

Explanation:

  • In a union, all members share the same memory space, and its size is determined by the largest data type inside it.
  • In this case, the union contains:
    • char ch; → 1 byte
    • int n; → typically 4 bytes
    • float f; → typically 4 bytes

How is Union Size Determined?

  • A union only allocates one memory block large enough to store the largest member.
  • Here, both int and float require 4 bytes each (assuming standard memory sizes).
  • So, the union size is determined by float, which is the largest.
  • If padding is involved (architecture-specific), it might be slightly larger to align the memory.

Example Code:

#include <stdio.h>

union temp {
    char ch;
    int n;
    float f;
};

int main() {
    printf("Size of union: %lu\n", sizeof(union temp));
    return 0;
}

Expected Output:

Size of union: 4

(If there's padding, it might be 8 bytes on some architectures.)

Final Answer:

(A) float

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.


Question analytics