Home » C++ » Variable Declaration in C++ Example

Variable Declaration in C++ Example

In C++, you can declare a variable anywhere in the block before you reference it. When the variable's declaration is close to its use, its purpose and behavior can be easier to understand. Below is an example of variable declaration in the C++ program.

Example 1: Variable Declaration in C++

#include <iostream>
main()
{
   cout << "Enter a number: ";
   int n;
   cin >> n;
   cout << "The number is: "<< n;
}

Output:

Enter a number: 123
The number is: 123

C++ isn't a memory-safe language. There's no guarantee that a variable has been assigned a value before it's used. When you define a variable, like:

int x;

A small block of memory is allocated to the variable. However, we have only declared the variable and not initialized it, which means that the block of memory that has been assigned to the variable still contains some value that has been left over from previous programs and operations. That value is called a garbage value. This may lead to erroneous results in programs.

To avoid this, declare and initialize variables like this:

int x = 0;

Reference: sof-42290149

See also: