Output of int sqrt(volatile int *ptr){ return (*ptr**ptr);}

Showing Answers 1 - 8 of 8 Answers

suba

  • Sep 26th, 2006
 

answer: 25

  Was this answer useful?  Yes

garanaveen

  • Sep 25th, 2010
 

This question is an interview question which is asked to test the possible
problems with the code if any.


This function is supposed to calculate the square of the number pointed by
ptr.

As it is volatile, its value can be changed outside the program too.

Since it declared as volatile no optimization is done by compiler on this
variable.


So for calculating the square of the integer pointed by ptr, if the value
changes between to fetch instructions of *ptr


This will be rewritten by the compiler as follows,


--------------------------

1. MOV R1, *PTR -> Access the value

2. MOV R2, *PTR -> (If the parameter were not volatile then this would have been
MOV R2, R1 as compiler optimizies this fetch instruction)

3. MULTIPLY R1, R2

4. MOV PRODUCT, R1

--------------------------


Here say at Instruction1, if the value of *PTR is 5

And then say at Instruction2, if the value of *PTR becomes 6.

Then the function returns 30 which is the square of neither 5 nor 6.


This code should be rewritten as,

int sqrt(volatile int *ptr)

{

int a = *ptr; //Typo in previous post!!

return (a*a);

}


so that it will either give the product of 5 (25) or 6 (36) depending on when
the value of *ptr changes!


--

Gara

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions