C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at die place of its first use. This makes the program much easier to write and reduces the errors that may be caused by having to scan back and forth. It also makes the program easier to understand because the variables are declared in the context of their use. The example below illustrates this point.
int main()
{
float x; // declaration
float sum=0;
for(int i=1;i<5;i++) { cin >> x;
sum=sum+x;
}
float average; //declaration
average=sum/i;
cout << average;
}
In C++, before we can use an object, we must define the object. A definition introduces the name of the object into the program, and it specifies the type of the object.
A common form of a C++ definition is a list of one or more valid identifiers. A knowledge typeld. Id…. Id; Where Type is a fundamental type or a type that has been previously defined by the programmer and Id is a C++ identifier. The definition
int x;
defines an object called x that has type int with no initial value. That is, the object is named, memory is allocated, but the object is given no initial value.
