C++ Variables C-PLUS-PLUS

C++ Variables  

C++ Variables

C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • double - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • string - stores text, such as "Hello World". String values are surrounded by double quotes
  • bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;
cout << myNum;

You can also declare a variable without assigning the value, and assign the value later. 

Example

#include <iostream>
using namespace std;

int main() {
  int myNum;
  myNum = 15;
  cout << myNum;
  return 0;
}
 

Output:

15

Constants

You can add the const keyword if you don't want to override existing values (this will declare the variable as "constant", which means unchangeable and read-only).

You can't change the value of constants during the program. You just can define its value at once during declaration.

Example

#include <iostream>
using namespace std;

int main() {
  const int myNum = 15;
  myNum = 10;
  cout << myNum;
  return 0;
}
 

Output:

In function 'int main()':
6.9: error: assignment of read-only variable 'myNum'

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries