Index
Variables
Variables in C++ act as containers for holding various types of data values.
Here are some common variable types and their descriptions:
- int: This type stores integers, which are whole numbers without decimals. Examples include 123 or -123.
- double: The double type stores floating-point numbers, which are numbers with decimals. Examples include 19.99 or -19.99.
- char: Char variables store single characters, such as ‘a’ or ‘B’. Char values are enclosed within single quotes.
- string: String variables hold text data, like “Hello World”. String values are enclosed within double quotes.
- bool: This type stores values with two states: true or false. It’s commonly used for Boolean logic and comparisons.
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Syntax
type variableName = value;
Where type is one of C++ types (such as int
), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.
Example:
int myNum = 2; // Integer (whole number without decimals)
double myFloatNum = 9.99; // Floating point number (with decimals)
char myLetter = 'C'; // Character
string myText = "Hello World"; // String (text)
bool myBoolean = true; // Boolean (true or false)