C++ Syntax:
Let's analyze and divide the given code for better understanding:
#include<iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Explanation of the code:
Line 1: The line "#include <iostream>" is a header file library that allows us to work with input and output objects, such as "cout" (used in line 5). Header files enhance the functionality of C++ programs.
Line 2: "using namespace std" means that we can use names for objects and variables from the standard library.
NOTE: If you find it difficult to comprehend how "#include <iostream>" and "using namespace std" work, don't worry. Just consider them as elements that typically appear in your program. (alert-success)
Line 3: This is a blank line. C++ ignores white space. However, we use it to enhance the readability of the code.
Line 4: Another standard feature of a C++ program is the "int main()" function. This function encompasses any code within its curly brackets {} that will be executed.
Line 5: "cout" (pronounced as "see-out") is an object used in conjunction with the insertion operator (<<) to output or print text. In our example, it will display "Hello World!".
Note: Every C++ statement concludes with a semicolon (;).
Note: The body of "int main()" could also be written as:
int main() { cout << "Hello World! "; return 0; }
Remember: The compiler disregards white spaces. Nonetheless, multiple lines contribute to the code's readability.
Line 6: "return 0" concludes the "main" function.
Line 7: It is important not to forget to include the closing curly bracket "}" to properly conclude the "main" function.
Output in C++:
C++ provides the ability to output values and print text using the "cout" object in combination with the "<<" operator:
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
You can include multiple "cout" objects to output different values or texts. However, it's important to note that it doesn't automatically insert a new line at the end of the output:
#include<iostream>
using namespace std;
int main()
{
cout << "Hello World!";
cout << "Welcome to CodeTechMentor!";
return 0;
}
Comments in C++:
In C++, comments are used to add explanatory or descriptive text within the source code that is ignored by the compiler. They serve as notes for developers and have no impact on the execution of the program. There are two types of comments in C++:
1. Single-line comments: Single-line comments begin with two forward slashes (//) and continue until the end of the line. Any text following the // symbol on the same line is considered a comment. Here's an example:
// This is a single-line comment.
cout << "Hello World!";
2. Multi-line comments: Multi-line comments, also known as block comments, allow you to comment on multiple lines of code. They begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). Here's an example:
/*
This is a multi-line comment.
It can span across multiple lines.
*/
cout << "Hello World!";
Multi-line comments are often used for longer explanations, documenting functions or classes, or temporarily disabling blocks of code.
It's important to note that comments are meant for human readers and should be used to make the code more understandable, especially for others who might read or maintain the code in the future. (alert-success)
Data Types in C++:
In C++, data types specify the type of data that can be stored in a variable. Some common built-in data types in C++ include:
- `int`: Used for storing integers (whole numbers).
- `float` and `double`: Used for storing floating-point numbers (decimal numbers).
- `char`: Used for storing individual characters.
- `bool`: Used for storing boolean values (`true` or `false`).
- `string`: Used for storing a sequence of characters.
Data Type |
Size (in bytes) |
---|---|
bool |
1 |
char |
1 |
int |
4 |
float |
4 |
double |
8 |
Variables in C++:
A variable is a named storage location that holds a value of a specific data type. Variables need to be declared before they can be used.
The syntax for declaring a variable is: `data_type variable_name = value;`. In C++, you define a variable by specifying its type (e.g., int) and giving it a name (e.g., x or myName). You can assign a value to the variable using the equal sign (=).
Here's an example:
Create a variable called Num that should store a number, look at the following code:
int Num = 10;
cout << Num;
You can also declare a variable without assigning the value, and assign the value later:
int Num;
Num = 20;
cout << Num;
Please note that in C++, if you assign a new value to a variable that already has a value, the previous value will be overwritten:
For example, let's say we have the following code:
int x = 5; // x is assigned the value 5
x = 10; // The value of x is updated to 10
cout << x; // 0utputs 10
Other Data Types:
int Num = 10; // Integer (whole number without decimals)
double Float = 12.66; // Floating point number (with decimals)
char Letter = 'A'; // Character
string Text = "Hello"; // String (text)
bool Boolean = true; // Boolean (true or false)
Identifiers in C++:
Identifiers are names given to variables, functions or any other user-defined entities in C++. They help identify and refer to these entities within the code. Some rules for naming identifiers in C++ are:
- Identifiers can include letters, digits, and underscores (_).
- The first character must be a letter or an underscore.
- Identifiers are case-sensitive (`age` and `Age` are different).
- Names cannot contain whitespaces or special characters like !, #, %, etc.
- Reserved keywords (e.g., `int`, `float`) cannot be used as identifiers.
White-Space in C++:
Whitespace | Explanation | Representation |
---|---|---|
New Line | To Insert a new Line | \n |
Tab | To Insert a Tab | \t |
Space | To Insert a Space | Empty Space |
Double Quote | To Insert a Double Quote Character | \" |
Backslash | To Insert a Backslash Character | \\ |
New Lines in C++:
- The escape sequence `\n` is used to represent a newline character.
- It is primarily used in output statements to insert a line break.
cout << "Hello World!\n";
- `endl` is a stream manipulator provided by the C++ Standard Library.
- It inserts a newline character into the output stream.
cout << "Hello World!" << endl;
User Input in C++:
#include<iostream>
using namespace std;
int main()
{
int number; // Variable to store the user's number input
cout << "Enter a number: "; // Prompting the user to enter a number
cin >> number; // Reading the user's number input
cout << "Number: " << number << endl; // Displaying the user's number input
return 0;
}
Type Conversion (Casting):
1. Implicit Casting:
int myInt = 10;
float myFloat = myInt; // Implicit casting from int to float
2. Explicit Casting:
- `static_cast`: Used for general type conversions between compatible types.
- `dynamic_cast`: Used for type conversions in polymorphic class hierarchies.
- `reinterpret_cast`: Allows conversion between unrelated types, such as casting a pointer to an integer type.
- `const_cast`: Used to remove the const or volatile qualifier from a variable.
float myFloat = 3.14;
int myInt = static_cast<int>(myFloat); // Explicit casting from float to int
It's important to note that not all type conversions are valid or safe. Care should be taken when performing type casting to avoid unexpected results or loss of data. (alert-success)
We will learn in detail about other types of explicit casting in later lectures.