C++ Variable

Hi everyone, inside this article we will see about C++ Variable.

A variable in C++ is a named location in memory where a value can be stored. The value stored in a variable can be changed during the execution of a program. A variable must be declared with a specific data type, which determines the size and layout of the memory allocated for the variable, as well as the type of values that can be stored in it.

For example, a variable of type “int” is used to store integer values, while a variable of type “double” is used to store floating-point values. Variables must be assigned a value before they can be used in a program.

Syntax

The syntax for declaring and initializing a variable in C++ is as follows:

data_type variable_name = value;

Example

int x = 10;
double y = 3.14;

In this example, x is an integer variable with the value of 10, and y is a double variable with the value of 3.14.

Rules for Defining Variables in C++

There are a few rules to follow when defining variables in C++:

  1. Variable names must begin with a letter or an underscore, and can contain letters, digits, and underscores.
  2. Variable names are case-sensitive, meaning x and X are considered to be different variables.
  3. Variable names cannot be the same as keywords, such as int or while.
  4. Variable names should be descriptive and meaningful, such as age or price.
  5. Variable names can be of any length, but it is best practice to keep them short and meaningful.
  6. Data types must be specified when declaring variables, such as int, double, char, or bool.
  7. Variables must be initialized with a value before they can be used in a program.
  8. The value of a variable can be changed during the execution of a program.
  9. Multiple variables of the same type can be declared on the same line, separated by commas.

Here’s an example of correctly declaring and initializing variables in C++:

int age = 30;
double price = 99.99;
char letter = 'A';
bool is_valid = true;

Invalid variable declaration:

int 4;    
int x y;    
int double;  

We hope this article helped you to understand about C++ Variable in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.