0% found this document useful (0 votes)
2 views42 pages

C++ Notes 1

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It also contrasts procedural programming with OOP, highlighting advantages such as code reusability and organization. Additionally, it covers the C++ character set, tokens, identifiers, keywords, constants, strings, special symbols, and operators, detailing their roles and rules within C++ programming.

Uploaded by

honeywagh9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views42 pages

C++ Notes 1

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It also contrasts procedural programming with OOP, highlighting advantages such as code reusability and organization. Additionally, it covers the C++ character set, tokens, identifiers, keywords, constants, strings, special symbols, and operators, detailing their roles and rules within C++ programming.

Uploaded by

honeywagh9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT II

Concepts of Object-Oriented Programming (OOP):-

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes
to structure software programs. It aims to implement real-world entities like inheritance, hiding,
polymorphism, etc., in programming. The main goal of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function

Key Concepts of OOP

Class

A class is a user-defined data type that acts as a blueprint for creating objects. It consists of data
members and member functions, which can be accessed and used by creating an instance of that
class. For example, a Car class may have properties like wheels, speed limit, and mileage

Object

An object is an instance of a class and represents real-life entities. It contains data and code to
manipulate the data. For example, a Dog object may have characteristics like color, breed, bark,
sleep, and eat

Data Abstraction

Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. For example, a driver knows that
pressing the accelerator increases the car's speed but does not know the inner mechanism

Encapsulation

Encapsulation is the wrapping up of data under a single unit. It binds together code and the data
it manipulates, hiding the data from other classes. For example, different sections in a company
handle their own data and do not allow direct access to other sections

Inheritance

Inheritance allows a class to derive properties and characteristics from another class. It enables
code reusability and reduces redundancy. For example, a Dog class can inherit properties from
an Animal class

Polymorphism

Polymorphism means having many forms. It allows a message to be displayed in more than one
form. For example, a person can be a father, a husband, and an employee at the same time

Dynamic Binding
UNIT II

Dynamic binding means that the code to be executed in response to a function call is decided at
runtime. It allows for more flexible and reusable code

Message Passing

Message passing is a form of communication used in OOP where objects communicate by


sending and receiving information. It involves specifying the name of the object, the name of the
function, and the information to be sent

Benefits of OOP

 Code Reusability: OOP allows for the creation of reusable components, leading to less
duplication and more efficient development3.

 Code Organization: It provides a clear and logical structure, making the code easier to
understand, maintain, and debug3.

 DRY Principle: OOP supports the "Don't Repeat Yourself" principle, minimizing code
repetition and leading to cleaner, more maintainable code3.

 Faster Development: By reusing existing code and creating modular components, OOP
allows for quicker and more efficient application development3.

Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program In object-oriented programming, the


is divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.
UNIT II

Procedural Oriented Programming Object-Oriented Programming

Object-oriented programming has


There is no access specifier in
access specifiers like private, public,
procedural programming.
protected, etc.

Adding new data and functions is not


Adding new data and function is easy.
easy.

Procedural programming does not have Object-oriented programming


any proper way of hiding data so it provides data hiding so it is more
is less secure. secure.

In procedural programming, overloading Overloading is possible in object-


is not possible. oriented programming.

In object-oriented programming, the


In procedural programming, there is no
concept of data hiding and inheritance
concept of data hiding and inheritance.
is used.

In procedural programming, the function In object-oriented programming, data


is more important than the data. is more important than function.

Procedural programming is based on Object-oriented programming is based


the unreal world. on the real world.

Object-oriented programming is used


Procedural programming is used for
for designing large and complex
designing medium-sized programs.
programs.

Procedural programming uses the Object-oriented programming uses the


concept of procedure abstraction. concept of data abstraction.
UNIT II

Procedural Oriented Programming Object-Oriented Programming

Code reusability absent in procedural Code reusability present in object-


programming, oriented programming.

C++ Character Set

The character set is a combination of English language comprising of the Alphabets and the White
spaces and some symbols from the mathematics including the Digits and the Special symbols. C++
character set means the characters and the symbols that are understandable and acceptable by the
C++ Program. These are grouped to create and give the commands, expressions, words, c-
statements, and some of the other tokens for the C++ Language.

It is basically the combination of alphabets or characters, special symbols, digits, and white spaces
that are similar as the learning English is to initially learns the alphabets, then learn how to combine
these alphabets to create words, which in turn are joined to make sentences and sentences are joined
to create the paragraphs. More about a C++ program we can say is that it is basically an order of the
characters arranged in a sequence. These characters come from the character set and play various
roles in many ways in the C++ compiler.

In addition to characters, C++ also uses a mixture of characters to represent some special conditions
as well. For example; Character combinations like ‘\nt, ‘\b’ and ‘\t’ are used for the representation
of the newline, backspace, and the horizontal tab correspondingly.

1. Alphabets

The alphabets are symbolized by A-Z & a-z, whichever is applicable. C- Language is case sensitive
so it always takes dissimilar meanings for the lower case and the upper case letters. By the use of
this character set C statements and character constants are writable very easily. Thus, all 26 letters
are usable in C-programming.

2. Digits

The digits are symbolized from 0-9 or by combining these digits together. With the use of digits, the
numeric constant is easily writable. The numeric data can also be assigned to the C-tokens as well.
All the 10 digits starting from 0 and ending at 9 are usable in the C-programming.
UNIT II

3. Special Symbols

All of the total keyboard keys excluding the alphabets, digits, and white spaces are termed as the
special symbols. Thus, these are some punctuation marks as well as some special symbols usable
for some special purpose or quotation.

There is a total of thirty special symbols that we can use in the C-programming. Moreover, special
symbols are usable for the C-statements like; to make an arithmetic statement +, -, * etc., for
creating relational statement <, >, <=, >=, == etc. , for creating assignment statement =, for creating
logical statement &&, II etc. are necessary.

4. White Spaces

White spaces have blank space, newline return, tab space (Horizontal), Form feed, carriage ctrl, etc.
are all usable for special purposes. Notably, Turbo-C Compiler always disregards these white space
characters in both high-level programming as well in low-level programming.

C++ Tokens

In C++, tokens can be defined as the smallest building block of C++ programs that the
compiler understands. Every word in a C++ source code can be considered a token.

Types of Tokens in C++

We have several types of tokens each of which serves a specific purpose in the syntax and
semantics of C++. Below are the main types of tokens in C++:

1. Identifiers

2. Keywords

3. Constants

4. Strings

5. Special Symbols

6. Operators
UNIT II

1. Identifiers

In C++, entities like variables, functions, classes, or structs must be given unique names within
the program so that they can be uniquely identified. The unique names given to these entities
are known as identifiers.

It is recommended to choose valid and relevant names of identifiers to write readable and
maintainable programs. Keywords cannot be used as an identifier because they are reserved
words to do specific tasks. In the below example, “first_name’ is an identifier.

string first_name = "Raju";

We have to follow a set of rules to define the name of identifiers as follows:

1. An identifier can only begin with a letter or an underscore(_).

2. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_). White
spaces and Special characters can not be used as the name of an identifier.

3. Keywords cannot be used as an identifier because they are reserved words to do specific
tasks. For example, string, int, class, struct, etc.

4. Identifier must be unique in its namespace.

5. As C++ is a case-sensitive language so identifiers such as ‘first_name’ and ‘First_name’


are different entities.

Here are some examples of valid and invalid identifiers in C++:


UNIT II

Valid Identifiers Invalid Identifiers

_name #name (Cannot start with special character except ‘_’)

Number89 2num (Cannot start with a digit)

first_name first name (Cannot include space)

_last_name_ string (Cannot be same as a keyword)

2. Keywords

Keywords in C++ are the tokens that are the reserved words in programming languages that
have their specific meaning and functionalities within a program. Keywords cannot be used as
an identifier to name any variables.

For example, a variable or function cannot be named as ‘int’ because it is reserved for
declaring integer data type.

There are 95 keywords reserved in C++. Some of the main Keywords are:

break try catch char class const continue

default delete auto else friend for float

long new operator private protected public return

short sizeof static this typedef enum throw

mutable struct case register switch and or


UNIT II

break try catch char class const continue

namespace static_cast goto not xor bool do

double int unsigned void virtual union while

3. Constants

Constants are the tokens in C++ that are used to define variables at the time of initialization
and the assigned value cannot be changed after that.

We can define the constants in C++ in two ways that are using the ‘const’ keyword and
‘#define’ preprocessor directive. Let’s see both methods one by one.

1. Define Constants using the ‘const’ Keyword in C++

Constants are the values that do not change during the execution of the program once defined.
We can make constant any type of data such as integer, float, string, and characters. A literal is
a constant value assigned to a constant variable.

Syntax

const data_type variable_name = value;

2. Define Constants using the ‘#define’ preprocessor directive in C++

#define preprocessor can be used to define constant identifiers and the identifier is replaced
with the defined value throughout the program where ever it is used. It is defined globally
outside the main function.

Syntax

// The constant_Name is replaced by its value throughout the program where ever it is used
#define constant_Name value

4. Strings
UNIT II

In C++, a string is not a built-in data type like ‘int’, ‘char’, or ‘float’. It is a class available in
the STL library which provides the functionality to work with a sequence of characters, that
represents a string of text.

When we define any variable using the ‘string’ keyword we are actually defining an object that
represents a sequence of characters. We can perform various methods on the string provided by
the string class such as length(), push_backk(), and pop_back().

Syntax of declaring a string

string variable_name;

Initialize the string object with string within the double inverted commas (“).

string variable_name = "This is string";

5. Special Symbols

Special symbols are the token characters having specific meanings within the syntax of the
programming language. These symbols are used in a variety of functions, including ending the
statements, defining control statements, separating items, and more.

Below are the most common special symbols used in C++ programming:

 Semicolon (;): It is used to terminate the statement.

 Square brackets []: They are used to store array elements.

 Curly Braces {}: They are used to define blocks of code.

 Scope resolution (::): Scope resolution operator is used to access members of namespaces,
classes, etc.

 Dot (.): Dot operator also called member access operator used to access class and struct
members.

 Assignment operator ‘=’: This operator is used to assign values to variables.

 Double-quote (“): It is used to enclose string literals.

 Single-quote (‘): It is used to enclose character literals.

6. Operators
UNIT II

C++ operators are special symbols that are used to perform operations on operands such as
variables, constants, or expressions. A wide range of operators is available in C++ to perform a
specific type of operations which includes arithmetic operations, comparison operations,
logical operations, and more.

For example (A+B), in which ‘A’ and ‘B’ are operands, and ‘+’ is an arithmetic operator
which is used to add two operands.

Types of Operators

1. Unary Operators

2. Binary Operators

3. Ternary Operators

1. Unary Operators

Unary operators are used with single operands only. They perform the operations on a single
variable. For example, increment and decrement operators.

 Increment operator ( ++ ): It is used to increment the value of an operand by 1.

 Decrement operator ( — ): It is used to decrement the value of an operand by 1.

2. Binary Operators

They are used with the two operands and they perform the operations between the two
variables. For example (A<B), less than (<) operator compares A and B, returns true if A is
less than B else returns false.

 Arithmetic Operators: These operators perform basic arithmetic operations on operands.


They include ‘+’, ‘-‘, ‘*’, ‘/’, and ‘%’

 Comparison Operators: These operators are used to compare two operands and they
include ‘==’, ‘!=’, ‘<‘, ‘>’, ‘<=’, and ‘>=’.

 Logical Operators: These operators perform logical operations on boolean values. They
include ‘&&’, ‘||’, and ‘!‘.

 Assignment Operators: These operators are used to assign values to variables and they
include ‘variables‘, ‘-=‘, ‘*=‘, ‘/=‘, and ‘%=’.

 Bitwise Operators: These operators perform bitwise operations on integers. They


include‘&’, ‘|’, ‘^’, ‘~’, ‘<<‘, and ‘>>‘.
UNIT II

3. Ternary Operator

The ternary operator is the only operator that takes three operands. It is also known as a
conditional operator that is used for conditional expressions.

Syntax:

Expression1 ? Expression2 : Expression3;

If ‘Expression1’ became true then ‘Expression2’ will be executed otherwise ‘Expression3’


will be executed.

Operator Precedence and Associativity in C

The concept of operator precedence and associativity in C helps in determining which


operators will be given priority when there are multiple operators in the expression. It is very
common to have multiple operators in C language and the compiler first evaluates the operater
with higher precedence. It helps to maintain the ambiguity of the expression and helps us in
avoiding unnecessary use of parenthesis.

In this article, we will discuss operator precedence, operator associativity, and precedence
table according to which the priority of the operators in expression is decided in C language.

Operator Precedence and Associativity Table

The following tables list the C operator precedence from highest to lowest and the associativity
for each of the operators:

Operator
Precedence Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)


1 Left-to-Right
. Dot Operator

-> Structure Pointer Operator


UNIT II

Operator
Precedence Description Associativity

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

2 (type) Cast Operator Right-to-Left

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

Relational less than, less than or


6 < , <= Left-to-Right
equal to
UNIT II

Operator
Precedence Description Associativity

Relational greater than, greater than


> , >=
or equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment


14 Right-to-Left
*= , /= Multiplication, division assignment

%= , &= Modulus, bitwise AND assignment


UNIT II

Operator
Precedence Description Associativity

Bitwise exclusive, inclusive OR


^= , |=
assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC

where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R = Relational, E


= Equality, B = Bitwise, L = Logical, T = Ternary, A = Assignment and C = Comma

Operator Precedence in C

Operator precedence determines which operation is performed first in an expression with more
than one operator with different precedence.

Example of Operator Precedence

Let’s try to evaluate the following expression,

10 + 20 * 30

The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be

10 + (20 * 30)

After evaluating the higher precedence operator, the expression is

10 + 600

Now, the + operator will be evaluated.


UNIT II

610

We can verify this using the following C program

[GFGTABS]C

// C Program to illustrate operator precedence

#include <stdio.h>

int main()

// printing the value of same expression

printf("10 + 20 * 30 = %d", 10 + 20 * 30);

return 0;

[/GFGTABS]

Output

10 + 20 * 30 = 610

As we can see, the expression is evaluated as,10 + (20 * 30) but not as (10 + 20) * 30 due to *
operator having higher precedence.

Operator Associativity

Operator associativity is used when two operators of the same precedence appear in an
expression. Associativity can be either from Left to Right or Right to Left.

Example of Operator Associativity

Let’s evaluate the following expression,


UNIT II

100 / 5 % 2

Both / (division) and % (Modulus) operators have the same precedence, so the order of
evaluation will be decided by associativity.

According to the given table, the associativity of the multiplicative operators is from Left to
Right. So,

(100 / 5) % 2

After evaluation, the expression will be

20 % 2

Now, the % operator will be evaluated.

We can verify the above using the following C program:

[GFGTABS]C

// C Program to illustrate operator Associativity


UNIT II

#include <stdio.h>

int main()

// Verifying the result of the same expression

printf("100 / 5 % 2 = %d", 100 / 5 % 2);

return 0;

[/GFGTABS]

Output

100 / 5 % 2 = 0

Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions.

Example of Operator Precedence and Associativity

In general, the concept of precedence and associativity is applied together in expressions. So


let’s consider an expression where we have operators with various precedence and associativity

exp = 100 + 200 / 10 - 3 * 10

Here, we have four operators, in which the / and * operators have the same precedence but have
higher precedence than the + and – operators. So, according to the Left-to-Right associativity
of / and *, / will be evaluated first.

exp = 100 + (200 / 10) - 3 * 10

= 100 + 20 - 3 * 10

After that, * will be evaluated,


UNIT II

exp = 100 + 20 - (3 * 10)

= 100 + 20 - 30

Now, between + and –, + will be evaluated due to Left-to-Right associativity.

exp = (100 + 20) - 30

= 120 - 30

At last, – will be evaluated.

exp = 120 - 30

= 90

Again, we can verify this using the following C program.

[GFGTABS]C

// C Program to illustrate the precedence and associativity

// of the operators in an expression

#include <stdio.h>

int main()

// getting the result of the same expression as the

// example

int exp = 100 + 200 / 10 - 3 * 10;

printf("100 + 200 / 10 - 3 * 10 = %d", exp);


UNIT II

return 0;

[/GFGTABS]

Output:

100 + 200 / 10 – 3 * 10 = 90

Important Points

There are a few important points and cases that we need to remember for operator associativity
and precedence which are as follows:

1. Associativity is only used when there are two or more operators of the same precedence.

The point to note is associativity doesn’t define the order in which operands of a single operator
are evaluated. For example, consider the following program, associativity of the + operator is
left to right, but it doesn’t mean f1() is always called before f2(). The output of the following
program is in-fact compiler-dependent.

Example

[GFGTABS]C

// Associativity is not used in the below program.

// Output is compiler dependent.

#include <stdio.h>

int x = 0;

int f1()

{
UNIT II

x = 5;

return x;

int f2()

x = 10;

return x;

int main()

int p = f1() + f2();

printf("%d ", x);

return 0;

[/GFGTABS]

Output

10

See this for details.

2. We can use parenthesis to change the order of evaluation

Parenthesis ( ) got the highest priority among all the C operators. So, if we want to change the
order of evaluation in an expression, we can enclose that particular operator in ( )
parenthesis along with its operands.

Example

Consider the given expression

100 + 200 / 10 - 3 * 10
UNIT II

= 90

But if we enclose 100 + 200 in parenthesis, then the result will be different.

(100 + 200) / 10 - 3 * 10 = 0

=0

As the + operator will be evaluated before / operator.

2. All operators with the same precedence have the same associativity.

This is necessary, otherwise, there won’t be any way for the compiler to decide the evaluation
order of expressions that have two operators of the same precedence and different associativity.
For example + and – have the same associativity.

3. Precedence and associativity of postfix ++ and prefix ++ are different.

The precedence of postfix ++ is more than prefix ++, their associativity is also different. The
associativity of postfix ++ is left to right and the associativity of prefix ++ is right to left.
See this for examples.

4. Comma has the least precedence among all operators and should be used carefully.

For example, consider the following program, the output is 1.

Example

[GFGTABS]C

#include <stdio.h>

int main()

int a;

a = 1, 2, 3; // Evaluated as (a = 1), 2, 3

printf("%d", a);

return 0;
UNIT II

[/GFGTABS]

Output

See this, this for more details.

5. There is no chaining of comparison operators in C

In Python, an expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining
doesn’t happen in C. For example, consider the following program. The output of the following
program is “FALSE”.

Example

[GFGTABS]C

#include <stdio.h>

int main()

int a = 10, b = 20, c = 30;

// (c > b > a) is treated as ((c > b) > a), associativity of '>'

// is left to right. Therefore the value becomes ((30 > 20) > 10)

// which becomes (1 > 10)

if (c > b > a)

printf("TRUE");

else

printf("FALSE");

return 0;
UNIT II

C++ Data Types

Last Updated : 14 Oct, 2024




All variables use data type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data they can store. Whenever
a variable is defined in C++, the compiler allocates some memory for that variable based on the
data type with which it is declared. Every data type requires a different amount of memory.

C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application. Data types specify the size and types of values to be
stored. However, storage representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical on all machines.

C++ supports the following data types:

1. Primary or Built-in or Fundamental data type

2. Derived data types

3. User-defined data types

To explore data types and their applications in detail, our Complete C++ Course covers primitive
and advanced data types with practical coding exercises.
UNIT II

Data Types in C++ are Mainly Divided into 3 Types:

1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char, float, bool, etc. Primitive data types
available in C++ are:

 Integer

 Character

 Boolean

 Floating Point
UNIT II

 Double Floating Point

 Valueless or Void

 Wide Character

2. Derived Data Types: Derived data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely:

 Function

 Array

 Pointer

 Reference

3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by
the user itself. Like, defining a class in C++ or a structure. C++ provides the following user-
defined datatypes:

 Class

 Structure

 Union

 Enumeration

 Typedef defined Datatype

Primitive Data Types

 Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of
memory space and range from -2147483648 to 2147483647.

 Character: Character data type is used for storing characters. The keyword used for the
character data type is char. Characters typically require 1 byte of memory space and range
from -128 to 127 or 0 to 255.

 Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean variable
can store either true or false. The keyword used for the Boolean data type is bool.

 Floating Point: Floating Point data type is used for storing single-precision floating-point
values or decimal values. The keyword used for the floating-point data type is float. Float
variables typically require 4 bytes of memory space.
UNIT II

 Double Floating Point: Double Floating Point data type is used for storing double-precision
floating-point values or decimal values. The keyword used for the double floating-point data
type is double. Double variables typically require 8 bytes of memory space.

 void: Void means without any value. void data type represents a valueless entity. A void data
type is used for those function which does not return a value.

 Wide Character: Wide character data type is also a character data type but this data type has
a size greater than the normal 8-bit data type. Represented by wchar_t. It is generally 2 or 4
bytes long.

 sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a
variable/data type in computer memory.

Example:

int m , x[50];

cout<<sizeof(m); //returns 4 which is the number of bytes occupied by the integer variable
“m”.

cout<<sizeof(x); //returns 200 which is the number of bytes occupied by the integer array
variable “x”.

The size of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.

C++

// C++ Program to Demonstrate the correct size

// of various data types on your computer.

#include <iostream>

4
UNIT II

using namespace std;

int main()

cout << "Size of char : " << sizeof(char) << endl;

cout << "Size of int : " << sizeof(int) << endl;

10

11

cout << "Size of long : " << sizeof(long) << endl;

12

cout << "Size of float : " << sizeof(float) << endl;

13

14

cout << "Size of double : " << sizeof(double) << endl;

15

16

return 0;
UNIT II

17

Output

Size of char : 1

Size of int : 4

Size of long : 8

Size of float : 4

Size of double : 8

Time Complexity: O(1)

Space Complexity: O(1)

Datatype Modifiers

As the name suggests, datatype modifiers are used with built-in data types to modify the length
of data that a particular data type can hold.
UNIT II

Data type modifiers available in C++ are:

 Signed

 Unsigned

 Short

 Long

The below table summarizes the modified size and range of built-in datatypes when combined
with the type modifiers:

Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535


UNIT II

Data Type Size (in bytes) Range

unsigned int 4 0 to 4,294,967,295

int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4 -3.4×10^38 to 3.4×10^38

double 8 -1.7×10^308 to1.7×10^308

long double 12 -1.1×10^4932 to1.1×10^4932

wchar_t 2 or 4 1 wide character

Note: Above values may vary from compiler to compiler. In the above example, we have
considered GCC 32 bit.
UNIT II

We can display the size of all the data types by using the sizeof() operator and passing the
keyword of the datatype, as an argument to this function as shown below:

Now to get the range of data types refer to the following chart

Note: syntax<limits.h> header file is defined to find the range of fundamental data-types.
Unsigned modifiers have minimum value is zero. So, no macro constants are defined for the
unsigned minimum value.

Macro Constants

Name Expresses

CHAR_MIN The minimum value for an object of type char

CHAR_MAX Maximum value for an object of type char

SCHAR_MIN The minimum value for an object of type Signed char

SCHAR_MAX Maximum value for an object of type Signed char

UCHAR_MAX Maximum value for an object of type Unsigned char

CHAR_BIT Number of bits in a char object

MB_LEN_MAX Maximum number of bytes in a multi-byte character

SHRT_MIN The minimum value for an object of type short int

SHRT_MAX Maximum value for an object of type short int


UNIT II

Name Expresses

USHRT_MAX Maximum value for an object of type Unsigned short int

INT_MIN The minimum value for an object of type int

INT_MAX Maximum value for an object of type int

UINT_MAX Maximum value for an object of type Unsigned int

LONG_MIN The minimum value for an object of type long int

LONG_MAX Maximum value for an object of type long int

ULONG_MAX Maximum value for an object of type Unsigned long int

LLONG_MIN The minimum value for an object of type long long int

LLONG_MAX Maximum value for an object of type long long int

ULLONG_MAX Maximum value for an object of type Unsigned long long int

The actual value depends on the particular system and library implementation but shall reflect
the limits of these types in the target platform. LLONG_MIN, LLONG_MAX, and
ULLONG_MAX are defined for libraries complying with the C standard of 1999 or later (which
only includes the C++ standard since 2011: C++11).

C++ Program to Find the Range of Data Types using Macro Constants

Example:
UNIT II

C++

// C++ program to Demonstrate the sizes of data types

#include <iostream>

#include <limits.h>

using namespace std;

int main()

cout << "Size of char : " << sizeof(char) << " byte"

<< endl;

10

11
UNIT II

cout << "char minimum value: " << CHAR_MIN << endl;

12

13

cout << "char maximum value: " << CHAR_MAX << endl;

14

15

cout << "Size of int : " << sizeof(int) << " bytes"

16

<< endl;

17

18

cout << "Size of short int : " << sizeof(short int)

19

<< " bytes" << endl;

20

21

cout << "Size of long int : " << sizeof(long int)

22

<< " bytes" << endl;

23
UNIT II

24

cout << "Size of signed long int : "

25

<< sizeof(signed long int) << " bytes" << endl;

26

27

cout << "Size of unsigned long int : "

28

<< sizeof(unsigned long int) << " bytes" << endl;

29

30

cout << "Size of float : " << sizeof(float) << " bytes"

31

<< endl;

32

33

cout << "Size of double : " << sizeof(double)

34

<< " bytes" << endl;

35

36
UNIT II

cout << "Size of wchar_t : " << sizeof(wchar_t)

37

<< " bytes" << endl;

38

39

return 0;

40

Output

Size of char : 1 byte

char minimum value: -128

char maximum value: 127

Size of int : 4 bytes

Size of short int : 2 bytes

Size of long int : 8 bytes

Size of signed long int : 8 bytes

Size of unsigned long int : 8 bytes

Size of float : 4 bytes

Size of double : 8 bytes

Size of wchar_t : 4 bytes

Time Complexity: O(1)

Space Complexity: O(1)

C++
UNIT II

#include <iostream>

#include <string>

using namespace std;

int main() {

// Integer data types

int a = 10;

short b = 20;

long c = 30;

10

long long d = 40;

11

cout << "Integer data types: " << endl;


UNIT II

12

cout << "int: " << a << endl;

13

cout << "short: " << b << endl;

14

cout << "long: " << c << endl;

15

cout << "long long: " << d << endl;

16

17

// Floating-point data types

18

float e = 3.14f;

19

double f = 3.141592;

20

long double g = 3.14159265358979L;

21

cout << "Floating-point data types: " << endl;

22

cout << "float: " << e << endl;

23

cout << "double: " << f << endl;

24
UNIT II

cout << "long double: " << g << endl;

25

26

// Character data types

27

char h = 'a';

28

wchar_t i = L'b';

29

char16_t j = u'c';

30

char32_t k = U'd';

31

cout << "Character data types: " << endl;

32

cout << "char: " << h << endl;

33

wcout << "wchar_t: " << i << endl;

34

cout << "char16_t: " << j << endl;

35

cout << "char32_t: " << k << endl;

36
UNIT II

37

// Boolean data type

38

bool l = true;

39

bool m = false;

40

cout << "Boolean data type: " << endl;

41

cout << "true: " << l << endl;

42

cout << "false: " << m << endl;

43

44

// String data type

45

string n = "Hello, world!";

46

cout << "String data type: " << endl;

47

cout << n << endl;

48

49
UNIT II

return 0;

50

Output

Integer data types:

int: 10

short: 20

long: 30

long long: 40

Floating-point data types:

float: 3.14

double: 3.14159

long double: 3.14159

Character data types:

char: a

wchar_t: b

char16_t: 99

char32_t: 100

Boolean data type:

true: 1

false: 0

String data type:

Hello, world!
UNIT II

You might also like