What is the output of the following ‘C’ program? (Assuming little – endian…
2018
What is the output of the following ‘C’ program? (Assuming little – endian representation of multi-byte data in which Least Significant Byte (LSB) is stored at the lowest memory address.)
#include<stdio.h>
#include<stdlib.h>
/* Assume short int occupies two bytes of storage */
int main ()
{
union saving
{
short int one;
char two[2];
};
union saving m;
m.two [0] =5;
m.two [1] =2;
printf(“%d, %d, %d\n”, m.two[0], m.two[1], m.one);
}/* end of main */
- A.
5, 2, 1282
- B.
5, 2, 52
- C.
5, 2, 25
- D.
5, 2, 517
Attempted by 83 students.
Show answer & explanation
Correct answer: D
Key idea: the union shares memory, and on a little-endian machine the first array element is the least significant byte (LSB).
Step 1: Identify stored bytes. After assignments, m.two[0] = 5 (LSB) and m.two[1] = 2 (MSB).
Step 2: Compute the short integer value from the two bytes. For a 16-bit short: value = (MSB * 256) + LSB = (2 * 256) + 5 = 512 + 5 = 517.
Step 3: Understand printf output. printf prints m.two[0] as 5, m.two[1] as 2, and m.one as the computed short value 517.
Answer: 5, 2, 517