c sharp Logo

Variables


C++ Variables

A variable is a named memory location that can store a value. Variables are used to store data that can be changed during the execution of a program.

To declare a variable in C++, you must specify the type of the variable and its name. For example:

int my_variable;

 

This declares a variable named my_variable of type int. The int type can store integer values.

Once a variable has been declared, you can assign a value to it using the assignment operator (=). For example:

my_variable = 10;

 

This statement assigns the value 10 to the variable my_variable.

You can then use the variable my_variable in your code. For example:

std::cout << my_variable << std::endl;

 

This statement will print the value of the variable my_variable to the console.

Identifiers

An identifier is a name that is used to identify a variable, function, class, or other entity in a C++ program. Identifiers must be unique and must follow certain rules.

Rules for C++ identifiers:

  • Identifiers can contain letters, digits, and underscores (_).
  • Identifiers must start with a letter or an underscore.
  • Identifiers cannot contain keywords or reserved words.
  • Identifiers are case-sensitive.

C++ Constants

A constant is a variable that cannot be changed during the execution of a program. Constants are declared using the const keyword.

For example, the following code declares a constant named PI of type double:

const double PI = 3.14159;

 

Once the constant PI has been declared, you cannot change its value.

Constants are useful for storing values that should not be changed, such as mathematical constants or the size of an array.

Example

The following example shows how to declare and use variables, identifiers, and constants in C++:

#include <iostream>

 

int main() {

  // Declare a variable.

  int my_variable = 10;

 

  // Declare a constant.

  const double PI = 3.14159;

 

  // Print the value of the variable to the console.

  std::cout << my_variable << std::endl;

 

  // Calculate the area of a circle.

  double area = PI * my_variable * my_variable;

 

  // Print the area of the circle to the console.

  std::cout << area << std::endl;

 

  return 0;

}

 

Output:

10

314.159