How to declare variables?
C++ could be a strongly-typed language, and needs each variable to be declared with its sort before its 1st use. This informs the compiler the scale to order in memory for the variable and the way to interpret its price. The syntax to declare a brand new variable in C++ is straightforward: we have a tendency to merely write the kind followed by the variable name (i.e., its identifier). For example:
These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier my number. Once declared, the variables a and my number can be used within the rest of their scope in the program.
If declaring more than one variable of the same type, they can all be declared in a single statement by separating their identifiers with commas. For example:
int a, s, c;
This declares three variables a, s and c, all of them of type int, and has exactly the same meaning as:
To see what variable declarations look like in action within a program, let’s have a look at the entire C++ code of the example about your mental memory proposed at the beginning of this
using namespace std;
int main ()
// declaring following integer variables:
int a, s;
// initialize variables:
a = 5;
s = 2;
a = a + 1;
// processing to compute result
result = a - s;
// displaying results
cout << result;
// As the return type of main function is int i have to return some integer to terminate this program:
The C++ language defines many headers, that contain info that’s either necessary or helpful to your program. For this program, the header <iostream> is required.
The line using namespace std; tells the compiler to use the std namespace. Namespaces area unit a comparatively recent addition to C++.
The next line ‘// main() is wherever program execution begins.’ may be a single-line comment out there in C++. Single-line comments begin with // and stop at the top of the road.
The line int main() is that the main function start wherever program execution begins.
The next line cout << “Hello World”; causes the message “Hello World” to be displayed on the screen.
The next line return zero; terminates main( )function and causes it to return 0 to the line method.
Don’t be worried if something else than the variable declarations themselves look a bit strange to you. Most of it will be explained in more detail in coming articles.