Variables and Constants

The first concept probably you need to know about any programming language is variableVariable is a memory location identified by a memory address that store some quantity of data referred to as a value.

You can define different types of variables based on the type of the data you plan to use in your application. Primitive data types are the first variable types you need to learn in any programming language. Arrays, Enumerations, Data Structures, Pointers, References and Classes are the other types of data type in C++.

Define a Variable

To define a variable, first you set the type of the variable and then you define the variable name or list of variable names which is separated by commas.

type variable1, variable2, ...;

For examples:

int a, j, k;
char key;
long[] matrix;

Define a Constant

To define a constant simply you can add const word before variable definition:

 const int DEFAULT_SIZE = 5;
#include <iostream>

const int DEFAULT_SIZE = 5;

int main() {
 std::cout << "Here is the value of DEFAULT_SIZE: ";
 std::cout << DEFAULT_SIZE << '\n';

 std::cout << "You cannot change the value of a constant" << '\n';

 std::cout << "But you can use its value in other expressions or as a function input." << '\n';
 int currentSize = 3 + DEFAULT_SIZE;
 std::cout << "For example: int currentSize = 3 + DEFAULT_SIZE: ";
 std::cout << currentSize << "\n";

   return 0;
}

$ g++ -o defconst defconst.cpp
 defconst.cpp:10:16: error: cannot assign to variable 'DEFAULT_SIZE' with const-qualified type 'const int'
   DEFAULT_SIZE = 6;
   ~~ ^ defconst.cpp:3:11: note: variable 'DEFAULT_SIZE' declared const here const int DEFAULT_SIZE = 5; ~~^~~
 1 error generated.

Leave a Reply