Hi,Pls tell me the importance of volatile in the below program and what is returned by the program. this program finds the square of a number. where are volatile variables exactly used in C programming ?int sqr(volatile int *ptr){ return (*ptr**ptr);}

Showing Answers 1 - 7 of 7 Answers

Sunyana

  • Sep 12th, 2006
 

hi..Volatile modifier is a directive to the compiler that this variable will not be optimised in certain ways.. here it will return the square of the integer passed in the function .. see this like ( (*ptr) * (*ptr ) )

  Was this answer useful?  Yes

BRN

  • Nov 22nd, 2006
 

Hello, For this program its not required to use volatile. Volatile says to the compiler two things.1- No optimization algo should be run on this variable.2- When ever u need the value of the volatile variable please take it from the memory .. don't trust the register for the latest value.Volatile variable not only can be updated by ur program but also the environment. Like status registers of any devise can be updated by only devises not ur program. Thats why the register lever program writers declares a status variable as const volatile .

  Was this answer useful?  Yes

anitha_c

  • May 30th, 2007
 

Hi,

In the above example, the use of volatile can lead to undesirable results. i.e it may not give the square of the number, the second *ptr access may be different from the first *ptr access since the variable is volatile, it can change unexpectedly.
So the correct way is
int sqr(volatile int *ptr)
{
 int i;

 i=*ptr;

return(i*i);
}

  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