Const

From Microduino Wiki
Jump to: navigation, search

Constant variable(const)

Const keyword is on behalf of the constants, which is a variable qualifier used to modify the properties of the variables to be read-only status. That means this variable is used just like any other variables in the same type, but the value of it can not be changed. If you try to assign a value to a const variable, it will report errors when compiling.

Constants defined by const obverse the rules of other variables variable under the government of scoping. This point, adding the defect of using #define, make the keyword const become a preferred method to define constants.

  • Example
const float pi = 3.14;
float x;
 
// ....
 
x = pi * 2;    // It won’t report errors when there are constants used in mathematical expression.  
pi = 7;        // Mistaken usage  - You can’t modify the value of a constant or resign a value to a constant. 

  • #define or const

You can use const or #define to create numbers or string constants. But for arrays, you can only use const. Generally, the #define corresponding to const is the preferred syntax to define constants.

[Return to Arduino Syntax Manual]