Basic Concepts of C++

Mannan Ul Haq
0

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: 

Here is a demonstration of different data types in C++:

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++:

In C++, whitespace refers to spaces, tabs, and newlines used for formatting and separation of code elements. Whitespace is generally ignored by the compiler and serves the purpose of enhancing code readability. Here are some examples of Whitespace:

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++:

In C++, the next line character `\n` and the stream manipulator `endl` are commonly used to introduce new lines in output statements. Here's an explanation of their usage:

1. `\n`:
  • The escape sequence `\n` is used to represent a newline character.
  • It is primarily used in output statements to insert a line break.
Example:

cout << "Hello World!\n";

2. `endl`:
  • `endl` is a stream manipulator provided by the C++ Standard Library.
  •  It inserts a newline character into the output stream.
 Example:

cout << "Hello World!" << endl;

User Input in C++:

Once you've become familiar with the usage of `cout` for outputting values, it's time to introduce `cin` for obtaining user input. `cin` is a pre-defined variable in C++ that enables reading data from the keyboard. It utilizes the extraction operator (`>>`) to retrieve input values.

Example:

#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):

Type casting in C++ refers to the process of converting one data type to another. It allows you to treat a variable of one type as if it were of another type. This can be useful in various situations, such as performing arithmetic operations or assigning values between different data types.

There are two main types of type casting in C++: implicit casting (also known as automatic casting) and explicit casting.

1. Implicit Casting:

Implicit casting occurs automatically by the compiler when it can safely convert one data type to another without any loss of information. For example, if you assign an integer value to a floating-point variable, the compiler will automatically convert the integer to a float.

int myInt = 10;
float myFloat = myInt; // Implicit casting from int to float

In this case, the value of `myInt` is implicitly cast to a float and assigned to `myFloat`.

2. Explicit Casting:

Explicit casting is performed by the programmer to explicitly convert a variable from one type to another, even if there is a potential loss of information. It is done by using casting operators and explicitly specifying the desired data type.

There are four types of explicit casting operators in C++:
  1. `static_cast`: Used for general type conversions between compatible types.
  2. `dynamic_cast`: Used for type conversions in polymorphic class hierarchies.
  3. `reinterpret_cast`: Allows conversion between unrelated types, such as casting a pointer to an integer type.
  4. `const_cast`: Used to remove the const or volatile qualifier from a variable.

Here's an example using `static_cast`:

float myFloat = 3.14;
int myInt = static_cast<int>(myFloat); // Explicit casting from float to int

In this case, the value of `myFloat` is explicitly cast to an int using `static_cast`.
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.


Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !