Type Conversion in C++

The data type of any variable tells us about the value you can store in that variable and what operations you can perform on it. It might be possible that one operation is supported by more than one data type and to handle such cases C++ allows us to convert one datatype to another datatype. This process of converting data type is known as Type Conversion or Type Casting.


In C++, there are two types of Type Conversion:

  • Implicit Type Conversion.
  • Explicit Type Conversion.


Implicit Type Conversion in C++.

Implicit type conversion is done automatically by the compiler wherever it is required in the program. It takes place when more than one data type is present in an expression. 

Let's understand with some examples of implicit type conversion. 

//Example of Implicit Type Conversion
#include<iostream>
using namespace std;

int main(){

  //conversion of int to bool type
  int value = 25;
  bool check = value;

  cout<<check<<endl;

  //conversion of double to int
  double pi = 3.14;
  int i = pi;

  cout<<i<<endl;

  //conversion of signed to unsigned
  unsigned int num = -1;

  cout<<num<<endl;

  return 0;
}
Output:
1
3
4294967295

We have observed the following points from the above example:
  • When we assign one of the non-boolean arithmetic types to a boolean object, the result is false if the value is 0 and true otherwise. 
  • When we assign a boolean to one of the arithmetic types, the result value is 1 if the boolean is true and 0 if the boolean is false. 
  • When we assign a floating-point value to an object of integral type, the value is truncated. It means the value before the decimal point will get stored. 
  • When we assign an integral value to a floating type then the fraction part is zero. 
  • When we assign a signed value to an unsigned value then it stores 2's complement of the value. 

You will observe from the above code that there is a chance of losing information in implicit type conversion. For example, when we try to store a floating value in an integer value we lose the value present after the decimal point. This usually happens when data of a larger type get converted to a smaller type. 

You can follow the below chart to check the Data Lose During Type Conversion.
  
Type Conversion Chart
Data Lose During Type Conversion

Explicit Type Conversion in C++.

In Explicit Type Conversion user manually change the data type from one type to another type based on the requirement. This process is also known as Type Casting. 

There are multiple ways for performing Explicit type conversion and here we are going to discuss them one by one.
  • Forceful Casting: In this type of casting you explicitly define the required datatype in front of the expression. 
syntax: (data_type) expression; 

//Example of Explicit Type Conversion
#include<iostream>
using namespace std;

int main(){

  float x = 3.14;

  int ans = (int)x * 4 * 4;
  cout<<ans<<endl;

  return 0;
}
Output:
48

Type Conversion Operators

C++ have four operators for performing type casting and they are:
  • Static cast
  • Dynamic cast
  • Const cast
  • Reinterpret cast
Example:
//C++ Example of Operator Type Conversion
#include<iostream>
using namespace std;

int main(){

  float x = 3.14;

  int ans = static_cast<int>(x);
  cout<<ans<<endl;

  return 0;
}
Output:
3

Data Types in C++.

Data Types are one of the most essential topics of any programming language that you should understand whenever you are learning any new programming language. The data type can be defined as which type of value a variable can store and what kind of mathematical, logical, and relational operations are allowed on those values.

In C++ programming, data types can be classified into the following groups:
  • Primitive/Built-in Datatypes.
  • Derived Datatypes.
  • User-Defined Datatypes.
data type in C++
There are several data types available in the C++ programming language.

Primitive Datatypes in C++.

Primitive data types are built-in datatypes that are already available to use in C++ programming languages. There are 7 primitive data types available in C++ programming and these are integers, float, double, character, boolean, void, and wide character. 

1. Integer
An integer data type is represented by the int keyword in C++  and each integer value takes up to 4 bytes of memory. The range of an integer-type variable is -2147483648 to 2147483647, this is the minimum and maximum value that you can store in an integer-type variable. Example: int num = 3450;

2. Floating point
A floating point data type is represented by the float keyword in C++ and is used to store decimals and exponential values. Each floating point value requires 4 bytes of memory. Example: float value = 45.15;

3. Double
Like floating data, Double data types are also used to store decimals and exponential values but double requires 8 bytes of memory because the precision of double is greater than float. Example: double value = 45.1502;

4. Boolean
Boolean datatype is represented by the bool keyword in C++ and can store only two types of values 'true' or 'false'. Example bool check = true;

5. Character
Character datatype is represented by the char keyword in C++ and requires 1 byte of memory. Characters are enclosed inside single quotes(' ') in C++. Example: char ch = 'a';

6. void
The term void means "no value" or "nothing", it is the keyword that is used to indicate the absence of data. There is no variable of type void, it is only used with those function which does not return any value.

7. Wide Character
Wide character (wchar_t) is the same as character data type but unlike char, it takes 2 or more bytes and is used to represent the character that requires more memory. Example: wchar_t w = L'A' 

Derived data types in C++

The data types that are derived from primitive or built-in data types are known as Derived Datatype. 

1. Function
A function is a block of code with a set of instructions that is used to perform a specific task. We create functions to avoid writing the same lines of code again and again. We can call the function anywhere inside the code whenever we want to perform that same task. 

Example: This function is used to perform the addition of two numbers and return a result of type integer.  
int sum(int a, int b){
  return (a + b);
}

2. Array
An array is a Linear Data Structure that can store elements of similar data types in a contiguous memory location. The main use of an Array is to store many values in just one variable. 
syntax: data_type ArrayName[size_of_array];

Example: int arr[5] = {2, 4, 6, 7, 1};

3. Pointers
A pointer is a variable that is used to hold the address of another variable. It stores the address of the variable having the same data type (integer pointer can hold the address of integer type variable). Example: int *ptr;

4. Reference
Reference is like an alternative name for another existing variable. It is represented by putting the '&' symbol in front of any variable. Example: int &ref = num;


User-Defined data types in C++

User-defined datatypes are created by users based on their requirements and they are created by using existing built-in data types.

1. Class
Class is a user-defined data type that has its own data members and member functions. It is a very important concept of object-oriented programming in C++. 
//Example of C++ class program
#include<iostream>
using namespace std;

class Addition{
  public:
  int result; //data member

  void add(int x, int y){ //member function
    result = x + y;
    cout<<"Result: "<<result;
  }
};

int main(){
  Addition obj;
  obj.add(5, 10);
  return 0;
}
Output:
Result: 15

2. Structure
A structure is a user-defined data type that is used to combine different data types into a single type. It is represented using the struct keyword in C++.
//Example of C++ structure program
#include<iostream>
using namespace std;

struct student{
  int rollNo;
  string name;
  char grade;
};

int main(){
  student std;
  std.rollNo = 10;
  std.name = "John";
  std.grade = 'A';

  cout<<std.name<<endl;
  cout<<std.rollNo<<endl;
  cout<<std.grade<<endl;

  return 0;
}
Output:
John
10
A

3. Enumeration
Enumeration is a user-defined data type denoted by an enum keyword in C++ and mainly use to assign names to integral constants.
//Example of C++ program to demonstrate enum
#include<iostream>
using namespace std;

enum week{
  Sunday,
  Monday,
  Tuesday,
  WednesDay,
  Thursday,
  Friday,
  Saturday
};

int main(){
  enum week day;
  day = Sunday;
  
  cout<<day;

  return 0;
}
Output:
0

4. Union
Union and Structure in C++ have almost the same features and both are user-defined data types. The only difference between them is that Union shares the same memory location. 
Example: Any change you will made in value x will be reflected in value y.
union test{
  int x, y;
};

5. Typedef
Typedef is used to explicitly define any new name to our existing data type. Example:
typedef long int ll;
ll num = 3439;


Datatype Modifiers in C++

A modifier is used to change the basic meaning of our built-in data types like int, float, double, and char so they fit precisely in various situations. There are four types of modifiers available in C++ and these are short, long, signed, and unsigned

Below is the list of datatypes and the amount of memory they required with the range of values that particular datatypes allow. 

Data Type Memory Size Range
int 4 Bytes -2,147,483,648 to 2,147,483,647
signed int 4 Bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 Bytes 0 to 4,294,967,295
short int 2 Bytes -32,768 to 32,767
unsigned short int 2 Bytes 0 to 65,535
unsigned long int 8 Bytes 0 to 4,294,967,295
long long int 8 Bytes -(2^63) to (2^63)-1
unsigned long int 8 Bytes 0 to 4,294,967,295
unsigned long long int 8 Bytes 0 to 18,446,744,073,709,551,615
signed char 1 Byte -128 to 127
unsigned char 1 Byte 0 to 255
wchar_t 2 Bytes or 4 Bytes 1 Wide Character
float 4 Bytes
double 4 Bytes
long double 12 Bytes

Escape Sequences in C++

Characters such as backspace or control characters have no visible image and they are nonprintable. Other characters (like single or double quotation marks question marks and backslash) have special meanings in the programming language and you cannot use any of these characters directly. Instead, you need to use an escape sequence to represent such characters.


An Escape Sequence begins with backslash (\) followed by a character or by a combination of digits. 


There are several escape sequences are defined in C++ programming language such as:

Escape Sequence Character Represented
\n New Line
\t Horizontal Tab
\b Backspace
\" Double quote
\' Single quote
\? Question Mark
\r Carriage Return
\a Alert (bell)
\\ Backslash
\f Form feed (new page)

C++ Example of Escape Sequences.
//Example of C++ Escape Sequence
#include<iostream>
using namespace std;

int main()
{
  cout<<"This is an example of \'single quotes\' and \"double quotes\"";
  cout<<"\nThis is an example of newline and \\backslash";
  cout<<"\nThis is an example of \t Horizontal tab and a\bbackspace";
  
  return 0;
}
Output:
This is an example of 'single quotes' and "double quotes"
This is an example of newline and \backslash
This is an example of    Horizontal tab and backspace

Conclusion:

Escape sequences in C++ are special character combinations that are used to represent characters that are difficult or impossible to type directly in a string or character literal. They begin with a backslash (\) followed by a specific character or sequence of characters.

Next:

Variables, Constant and Literals in C++

In this article, we will discuss variables, constants, and literals in C++ programming language with examples.


C++ Variables

In programming, variables are containers for storing data values. It is basically a name given to a memory location and this name must be unique, you cannot use the same variable name for two different memory locations. The value that you will store in a variable can be changed during the execution of the program. 

syntax: data_type variable_name;
example: int count = 10;
variables in C++
Variables in C++
Rules for deciding a variable name:
  • A variable name can contain only alphabets, digits, and underscores. 
  • A variable name must begin with an alphabet or underscore, it cannot begin with a number.
  • A variable name should not contain any whitespace or special characters like #, $, @, %, *, etc.
  • A variable name is case-sensitive in nature. Ex: num and Num is two different variables.
  • One cannot use C++ reverse keywords (Ex: int, float, for) as a variable name. 
Note: It is suggested to start a variable name with lowercase alphabets and try to give always meaningful variable names. (alert-success)


C++ Constant

In C++ programming, constants are those kinds of variables whose values are fixed and cannot be changed. These kinds of variables are defined using the const keyword and they have read-only property. Example: 

const float PI = 3.14
PI = 3.141 //Error: value of PI is constant

C++ Literals

Values such as numbers, characters, or strings of characters whose values are self-evident are known as literals. These values you can use directly in your C++ code. Example: 4, 5.6, 'c', 3.14156e3, 0x19, etc. 

Different kinds of literals present in C++ programming:

1. Integer Literals: Integer literals are those numbers that do not have any decimal point or exponential part. We can write an integer literal using decimal, octal or hexadecimal notation.
  • Decimal (base 10): It is the Normal representation of numbers that we use in daily life. Ex: 25
  • Octal (base 8): Integer literals that begin with 0 are interpreted as octal. Ex: 031 is an octal representation of 25.
  • Hexadecimal (base 16): Integer literals that begin with 0x or 0X are interpreted as hexadecimal. Ex: 0x19 is a hexadecimal representation of 25.
//C++ example of Integer Literals
#include<iostream>
using namespace std;

int main()
{
    int x, y, z;
    x = 25;
    y = 031;
    z = 0x19;

    cout<<"Decimal Representation: "<<x<<endl;
    cout<<"Octal Representation: "<<y<<endl;
    cout<<"Hexadecimal Representation: "<<z<<endl;

    return 0;
}
Output:
Decimal Representation: 25
Octal Representation: 25
Hexadecimal Representation: 25

In the above code, you can observe that all three different integer variables represent the same value 25 in C++ programming.

2. Floating point Literals: Floating-point literals include either a decimal point or an exponent (indicated by either E or e) that is specified using scientific notation. 
Example:
3.52341
3.52341E2 = 3.52341x10^2 = 352.341
3.52341e2 = 3.52341x10^2 = 352.341
3.52341E-1 = 3.52341x10^-1 = 0.352341

//C++ example of Floating Point Literals
#include<iostream>
using namespace std;

int main()
{
    float x, y, z, n;
    x = 3.52341;
    y = 3.52341E2;
    z = 3.52341e3;
    n = 3.52341E-1;

    cout<<x<<endl;
    cout<<y<<endl;
    cout<<z<<endl;
    cout<<n<<endl;

    return 0;
}
Output:
3.52341
352.341
3523.41
0.352341
  
3. Character Literals: A character enclosed with single quotes are known as a character literal. Ex: 'a', '4', '{', etc.

4. String Literals: When zero or more characters are enclosed in double quotation marks is known as a string literal. Ex: "fruit", "code", " ", "c", "\nHello World", etc.
Note: The compiler appends a null character ('\0') to every string literal. Thus, the actual size of a string literal is one more than its apparent size. (alert-success)
You can read our article, character vs string class in C++ to understand the difference between them.

Using Namespace in C++.

If you are already familiar with C++ programming then you must have seen this line "using namespace std" on top of the code after including all required header files. Many beginners consider this as a part of C++ syntax without trying to understand its exact meaning. In this article, we will discuss namespace and why we use it.


What is Namespace in  C++?

A namespace is a declarative region that provides a scope to the identity functions or variables inside it. They are used to organize code into logic groups and prevent name collisions, mainly when the code base includes multiple libraries. 


Let's understand it using one example condition: 

#include<iostream>

int main()
{
    int n = 0;
    std::cout<<"Enter a number: ";
    std::cin>>n;
    std::cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above example code, we have used std::cout and std::cin instead of simply using cout and cin. The prefix std:: indicates that the name cout and cin are defined inside the namespace named std which stands for "standard library".

A using-declaration lets you use a name from a namespace without qualifying the name with a namespace_name::prefix. 
  • syntax: using namespace::name;
C++ Example code:
#include<iostream>
using std::cin;
using std::cout;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above code example, you will notice that we are using cout and cin without std:: because we have already defined that we are using cin and cout from the std namespace so we don't have to write std:: again, and again.

C++ using namespace std Example.

using namespace std in C++ code indicates that any name that we are going to use in our code belongs to the std (standard library) namespace. It is mainly used for our input/output operations.
#include<iostream>
using namespace std;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5
 

Input/Output stream in C++.

The C++ programming language does not define any statement to perform input and output operations. Instead, C++ has a separate input/output library that is part of the C++ standard library that provides primary input/output and many other facilities.


For the purpose of input and output, you will use the iostream (input-output stream) library which is a part of the C++ standard library. You need to include iostream header file on top of any C++ code file to use the properties define in this library. 

#include<iostream> //header file

int main()
{
   //include the rest of your code here
}


Note: A stream is a sequence of characters read from or written to an Input/Output device. 

  • When the direction of the flow of characters is from the device to the main memory then this process is called input.
  • When the direction of the flow of characters is from the main memory to the device then this process is called output


There are basically four standard objects present inside the iostream library and these are:

Objects Uses
std::cin (pronounced see-in) Standard input
std::cout (pronounced see-out) Standard output
std::cerr (pronounced see-err) Standard error
std::clog (pronounced see-log) General information

std::cout
cout is an object of the standard ostream (output stream) class that is defined in the iostream library. It is used to print the output on the display screen (console). The insertion operator (<<) to insert in the output stream to display the text to the console.
#include<iostream> //header file

int main()
{
    std::cout<<"Hello AlgoLesson"; //printing Hello AlgoLesson on console
    std::cout<<4;  //printing 4
return 0; }
Output:
Hello AlgoLesson4

std::cin
cin is an object of the standard istream (input stream) class that is defined in the iostream library. It is used to take input from the user using an input device like a keyboard. The extraction operator (>>) extracts the data from the cin object which is entered by the user. 
#include<iostream> //header file

int main()
{
    int x; //variable to hold input

    std::cout<<"Enter the value of x: ";
    std::cin>> x; //getting input from keyboard and store in x

    std::cout<<"Value of x: " << x ;
    return 0;
}
Output:
Enter the value of x: 7
Value of x: 7

std::cerr
cerr is a standard error stream that is part of the iostream class and is used to print the error messages. This is used when a person wants to show an error message immediately. 
#include<iostream> //header file

int main()
{
    std::cerr <<"This is an error message";
    return 0; 
}
Output:
This is an error message

std::clog
clog is a standard buffered error stream that is used to store general information or error messages. It is also part of the iostream library and is used to display error messages on the display screen.
#include<iostream> //header file

int main()
{
    std::clog <<"This is an error message log";
    return 0; 
}
Output:
This is an error message log

std::endl
endl stands for "end line" which is used to tell the console to move the cursor to the next line so we can print the output in a new separate line. You can also use '\n' which is a newline character instead of using endl.
#include<iostream> //header file

int main()
{
    std::cout <<"Welcome to AlgoLesson" << std::endl;
    std::cout <<"You are learning C++"; 
    return 0; 
}
Output:
Welcome to AlgoLesson
You are learning C++

Comments in C++ Programming.

Comments are the text that is added in C++ code to make it more readable and easy to understand. It is basically added for future reference so that whoever is going to work on that code will get additional information from comments that help them to understand the code. The compiler treats comments as white space and completely ignores them.


Two types of comments are available in the C++ programming language, single-line comments, and multi-line comments.


Single Line Comment.

Single-line comments in C++ start with two forward slashes (//) and any text written after this till the end of the line is considered a single comment.  

Example of single-line comment in C++:

//This is a single-line comment

//initializing an integer variable with value 5
int a = 5;

int a = 10; //updating value of a


Multi-line Comment.
The multi-line comment starts in C++ start with /* and ends with */ and any text between them are considered white space and ignored by the compiler. If you start a multi-line comment by using /* but forget to close it then everything after /* will get commented on.

Example of Multi-line comment in C++:
/*Below code will print the message "Hello World on the 
console using cout function which stands for character function.
*/
std::cout<<"Hello World";

Single-line comments are mostly used for writing short comments and Multi-line comments are used for writing longer comments.

Introduction to C++ Programming.

Introduction to C++ Programming.

The C++ program was developed by Bjarne Stroustrup in 1979 at Bell Lab which is basically an extended version of the C program. After the release of C++ in 1998 by ISO five major updates have been made in the language (C++ 03, C++11, C++14, C++17, C++20), and each time more new functionality has been added.


The initial version of C++ was called "C with Classes" having extra features like data abstraction, object-oriented programming, and generic programming. 


Usage of C++ Programming Language.

  • It is used for making Video Games.
  • It is used for making High-Performance Financial Applications.
  • It is used for making Embedded Software.
  • It is used in Artificial Intelligence and Neural Networks.
  • It is used for Developing a Web Browser.
  • It is used for building Operating Systems.


C++ is a high-level programming language and a single statement of C++ may compile into many machine language instructions. Let's understand the basic syntax of C++ programming in detail by using below simple example. 

#include<iostream>

int main()
{
    std::cout<<"Hello AlgoLesson";
    return 0;
}
Output:
Hello AlgoLesson

Let's understand each line of the above code one by one:

Line 1: It is a Preprocessor directive telling that you have included iostream header file which is part of the C++ standard library. The iostream library allows us to read and write from or to the console.

Line 2: It is a blank space that will be ignored by the compiler. It is not necessary to give this blank space but it helps read the code more efficiently. 

Line 3:  In this line, you are defining the main function and every C++ program must have this special main function. Whenever you run the program, all the statements inside the main function will execute in sequence order and the program gets terminated when the last statement of the main function has been executed.

Line 4 and Line 7: These two lines indicate the opening and closing brackets that define the function body and tell the compiler which are lines that belong to the main function.

Line 5: This statement helps you to print your output on the console (cout stands for character output) and the << operator is used to send the output character to the console. In our case, we are sending "Hello AlgoLesson" to the console.

Line 6: It is a return statement which is the last statement of the program that sends a value back to the operating system in order to indicate whether the program has been successfully executed or not. 

What is Syntax Error in Programming?

The syntax is basically specific rules that you need to follow for writing code and different programming languages have their own syntax. You need to write each statement by following these rules in order to write a good program. 

For example, all statements in C++ programming must end with a semicolon. If you make any mistake in the syntax of the program then while running the code your compiler will send you a syntax error with a short message describing the possible cause of the error. 

Syntax Error in C++ Programming
C++ Syntax Error when you miss a semicolon

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson