Constant and Volatile variable

CONSTANT

Constants - Like a Rule That Never Changes

Imagine you have a rule at home, like "Always wash your hands before dinner." In C language, constants are a bit like that – values that never change during the program's execution.

We use #define to create a constant named SPEED_OF_LIGHT with the value 299792458. This is a rule that should never change.

If you try to change the value of SPEED_OF_LIGHT later in the program (uncomment the line), it will result in a compilation error. Constants are like rules you set at the beginning, and you stick to them.

When you run the program, it prints the value of the constant.


VOLATILE

Volatile Variables - Always Paying Attention
Now, imagine you have a friend who's always paying attention, no matter what. In C language, volatile variables are a bit like that – variables that can change unexpectedly, and the compiler should always check their current value.

We declare a variable named sensorValue as volatile. This tells the compiler that the value of this variable can change unexpectedly, for example, if it's being updated by external hardware like a sensor.

Inside an infinite loop, we simulate the sensor updating its value by incrementing sensorValue and printing the current value.

Because sensorValue is marked as volatile, the compiler knows that it should always check the actual memory location of the variable, even if it looks like nothing has changed in the code.

Constants are values that don't change during the program and are defined using #define.

Volatile variables are used when a variable's value can change unexpectedly, and the compiler should always check its current value, even if it seems unnecessary.



Post a Comment

0 Comments