Variable Types & Scope in C++

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this section of the C++ tutorial, we will have a look at types of variables & scope in C++. Variable is used when any value that changes in the program needs to be saved. The variable can be declared with different memory requirements and functioning in multiple ways. The variable is the memory location name assigned to the compiler according to the variable data type.

Variable Types in C++

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.

Syntax to declare the variable in C++

type variable = value;

Scope of Variables

All the variables have their operating area, and they don’t hold their value out of that boundary, this boundary is called the variable’s scope. In most cases, it is between the curly braces, where a variable is declared to exist, not outside. We will study the storage classes later, but we can now split variables widely into two main types:
  • Global Variables: Once declared and can be used throughout the lifetime of the program by any class or any function.
  • Local variables: It exists only between the curly braces, in which it’s declared.

Special types of variable

There are also some special keywords to give the variables in the program unique characteristics. Most of the following two are used, they will be discussed in detail later.

  1. Final – Once initialized, its value cant be changed.
  2. Static – These variables hold their value between function calls.

Leave a Comment

Your email address will not be published. Required fields are marked *