Skip to content

ISRO Scientist/Engineer CSE 2018Programming in C › Program Output and Loops

ISRO Scientist/Engineer CSE 2018 PYQ: Consider the following program { int x=1; printf("%d",(*char(char*)&x)); } Assuming required header files…

Consider the following program

{
    int x=1;
    printf("%d",(*char(char*)&x));
}

Assuming required header files are included and if the machine in which this program is executed is little endian, then the output will be

  1. A
    0
  2. B
    99999999
  3. C
    1
    Correct answer
  4. D
    unpredictable

Answer

(C) 1

Approach

As literally printed the expression printf("%d", (char(char)&x)); is not valid C: char(char*)&x tries to use the type name char as a function, and char is meaningless. The handwritten sheet accompanying the question writes the same expression and draws an arrow under the char( token, indicating that this is the malformed spelling of the classic byte-inspection idiom, i.e. (char*)&x (equivalently (char)(char*)&x). Evaluating that idiom: x = 1 occupies a 32-bit int as 0x00000001. On a little-endian machine the least significant byte is stored at the lowest address, so the four bytes at &x are 01 00 00 00 (as the handwritten note itself shows: the 00000001 byte comes first). (char*)&x converts the int* to a char* pointing at that lowest address, and dereferencing it reads exactly one byte, 0x01. Since 0x01 is below 0x80, the value is 1 whether char is signed or unsigned. This char value is then promoted to int by the default argument promotions of a variadic call, so printf("%d", ...) prints 1. The other options are wrong for concrete reasons: 0 results only from reading the most-significant byte (0x00), which happens on a big-endian machine or from a higher address, contradicting the stated little-endian assumption; 99999999 is not a value any byte of 0x00000001 can produce; and unpredictable is ruled out because endianness is fixed and a char is at least 8 bits, so the byte read is deterministic. The answer is therefore 1, option C.

Reviewed by ISRO IQ Editorial Team.