in Programming edited by
3,142 views
8 votes
8 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 edited by
by
3.1k views

2 Answers

8 votes
8 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

See, I have executed the code in the compiler as well.

It is never going to come $22$.

ISRO has made so many blunders already.

0
0

In 13th Edition of Let us C, associativity of comma is written as right to left but on internet it is from left to right.

Which one is correct?

1
1
622 % 256 = 110

622 % 3 = 1

110*1 = 110 (answer)
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