in Programming in C retagged by
5,652 views
12 votes
12 votes

What is output of the following ‘C’ code assuming it runs on a byte addressed little endian machine?

#include<stdio.h>
int main()
{
    int x;
    char *ptr;
    x=622,100,101;
    printf("%d",(*(char *)&x)*(x%3));
    return 0;
}
  1. $622$
  2. $311$
  3. $22$
  4. $110$
in Programming in C retagged by
by
5.7k views

2 Answers

14 votes
14 votes
Best answer

$\underline{\mathbf{Answer:}\Rightarrow}\;\;\mathbf{(d)}$

$\underline{\mathbf{Explanation:}\Rightarrow}\;$

$\underline{\textbf{Big-endian}:}$

It is the order in which the $\color{green}{\text{"big end" (most significant value in the sequence(MSB)}}$ is stored first $\color{green}{\text{at the lowest storage address}}$.

$\underline{\textbf{Little-endian}:}$

It is an order in which the $\color{green}{\text{"Little end" (LSB)}}$ is stored first.


Now the associativity of the comma (,) is from $\color{red}{\text{left to right.}}$

Also, the $\color{blue}{\text{precedence of the comma is lower than the equal to “=” operator}}$.

So, $\mathbf x$ will store only $\mathbf{622}$

Now, Binary value of  $\mathbf{622}$ is given by $\underbrace{{\mathbf{00000010 \mid 01101110}}}_\text{= 622 in decimal representation}$

$\mathbf{\underbrace{00000010}_\text{MSB} \mid \underbrace{\color{magenta}{01101110}}_\text{LSB(110 in decimal form)}}$

$\underline{\color{blue}{\text{$\because$ Little-endian will store only lower bytes.}}}$

So, $\mathbf{110\;(decimal\;value)}$ will only be stored in $\mathbf x$.

$\therefore \; 110\times \underset{\color{green}{\mathrm x \% 3}}{1} = 110$

$\therefore \mathbf{(d)}$ is the correct option.

edited by
by

4 Comments

622 % 256 = 110

622 % 3 = 1

110*1 = 110 (answer)
0
0

@ @

(char*)&x is noting but typecasting integer pointer to char pointer.

 

what use of one extra * before it? (*(char *)&x)*(x%3))

0
0
it means reading 1 byte from the address (&x) because it is typecast as * character pointer.
0
0
2 votes
2 votes

$x= 622, 100, 101$, Comma work as separator here and $=$ operator has higher precedence than ',' operator. so $x$gets initialized by $622$

$622$ binary notation is : $1001101110$

$x$%$3$ will give $1$.

(*(char *)& $x$) gives $01101110 = 110$

Hence $110*1 = 110$ is correct answer

 

2 Comments

How x%3 is 1
0
0
x = 622

So, 622 % 3 = 1
0
0
Answer:

Related questions