C++ Lec2-Comments & Variables
C++ Lec2-Comments & Variables
C++ Lec2-Comments & Variables
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.
Any text between // and the end of the line is ignored by the compiler (will not be executed).
Example
#include <iostream>
using namespace std;
int main() {
// This is a comment
cout << "Hello World!";
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!"; // This is a comment
return 0;
}
Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored
by the compiler:
Example
#include <iostream>
Single or multi-line comments?
using namespace std;
return 0; }
C++ Variables
In C++, there are different types of variables (defined with different keywords), for example:
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
The general rules for constructing names for variables (unique identifiers) are:
To create a variable, you must specify the type and assign it a value:
Syntax
Where type is one of C++ types (such as int), and variable is the name of the variable (such as x
or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called Num of type int and assign it the value 15:
#include <iostream>
int main() {
return 0;
You can also declare a variable without assigning the value, and assign the value later:
Example
#include <iostream>
int main() {
int Num;
Num = 15;
return 0;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
#include <iostream>
int main() {
return 0;
}
Programming C++ Samir Bilal Practical & Theoretical
6
Other Types
Example
You will learn more about the individual types in the Data Types chapter.
Q1) what is c++ comments? What is single-line comment? What is multi-line comment?
Q4) what are the general rules for constructing names for variables?