Declaration of variables - Rules for declaration of variables with examples |
Declaration of variables:
- A variable is a named storage location that can store a value of a particular data type.
- In other words, a variable has a name, a type and stores a value.
- In order to use a variable in C++, we must first declare it specifying which data type we want it to be.
- The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier.
- type nameOfTheVariable(identifier);
Examples:
- int number;
- float floatNumber;
- int firstNumber, secondNumber, thirdNumber;
- You can declare one variable in one statement .
- You could also declare many variables in one statement separating with commas (as in the third statement).
An identifier is needed to name a variable C++ imposes the following rules on identifiers:
- An identifier is a sequence of characters, of up to a certain length (compiler-dependent, typically 255 characters), comprising uppercase and lowercase letters (a-z, A-Z), digits (0-9), and underscore "_".
- White space (blank, tab, new-line) and other special characters (such as +,-,*,/,@,&, commas, etc.) are not allowed.
- An identifier must begin with a letter or underscore. It cannot begin with a digit.
- An identifier cannot be a reserved keyword or a reserved literal (e.g.,int,double,if,else,case,class,char,sizeof,for).
- Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
Variable Naming Convention:
A variable name is a noun, or a noun phrase made up of several words. The first word is in lowercase, while the remaining words are initial-capitalized, with no spaces between words.
Examples:
firstNumber,leftNumber,xTopLeft and thisIsAVariableName.This convention is also known as camel-case
0 Comments