0% found this document useful (0 votes)
38 views57 pages

Unit 2 Basics of C Programming

This document discusses the basics of C++ programming structure. It explains that C++ programs have three main sections: the standard library section, main function section, and function body section. The standard library section includes header files, the main function section is where program execution begins, and the function body section contains the code to be executed. The document also covers other C++ fundamentals like data types, operators, memory management, and more.

Uploaded by

Nabin Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
38 views57 pages

Unit 2 Basics of C Programming

This document discusses the basics of C++ programming structure. It explains that C++ programs have three main sections: the standard library section, main function section, and function body section. The standard library section includes header files, the main function section is where program execution begins, and the function body section contains the code to be executed. The document also covers other C++ fundamentals like data types, operators, memory management, and more.

Uploaded by

Nabin Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 57

Basics of C++ programming

Unit 2
Intro
• C++ is an OOP language
• Developed by Bjarne Stroustrup at AT &T and bell laboratories
• Combination of power of C and additional feature of OOP
resulted in C++
• C++ can be used to develop editors, compilers, databases,
communication systems and any real life complex application
systems
Structure of C++ program
• C++ is structured by dividing a program into three sections:
– Standard Library Section
– Main Function Section
– Function Body Section
• For example lets look at an example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
Structure of C++ program(cont..)
Standard Libraries Section
• #include is a preprocessor command that copies and paste
entire text specified between angle bracket into the source
code
• <iostream> is a standard file that contains commands for
displaying and getting input from the user
• Namespace is a prefix applied to all the names

Main Function Section (int main{})


• The starting point of C++ programs is the main function
• This function is called by OS when the program is executed
• { tells start of code and } tells end of code
Structure of C++ program(cont..)
Function Body Section

cout << "Hello World" << endl;


return 0;
• cout is short for character output and displays whatever in
between <<
• Return keyword tells program to return value to a function int
main()
• After return statement, execution control returns to OS
component
• Execution of code terminates here
Structure of C++ program(cont..)
It includes the following:
• Include files
• Class declaration
• Class functions, definition
• Main function program
Comments in C++
Output Operator
• cout << “Hello world”;
• cout can be used to display individual
character, strings and numbers
• It is an object that corresponds to standard
output stream
• The insertion operator << also called “put to”
operator inserts information from its right to
the object on its left
Input Operator
• cin >> number;
• The statement above causes the program to
wait for the user to type in a number. The
number typed is place in number variable.
• cin is predefined identifier in C++ that
corresponds to standard input stream
• >> is known as get from operator or extraction
operator. It extracts value from keyboard and
assigns it to the variable on its right.
Cascading of I/O operator
cout << ”sum=” << sum << ”\n” ;

cout << ”sum=” << sum << ”\n” <<


”average=” << average <<”\n”;

cin >> number1 >> number2;


Tokens
• The smallest units in program are known as
tokens. C++ has the following tokens
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators
Tokens (Keywords)
• They are the explicitly reserved identifiers and can’t be used as names for
program variables or user defined program elements
Tokens (Identifiers)
• It refers to the name of variable, function, array, class,
etc.
• Each language has its own rule for naming identifiers
• The following are basic rules for C and C++:
1. Only alphanumeric chars, digits and under score are permitted
2. The name can’t start with digit
3. Upper case and lower case are distinct
4. A declared keyword can’t be used as variable name

Note: In C the max length of variable is 32 chars but in C++ there is no


limit
Basic data types in C++
Built in Data Types
Type Bytes Range
char 1 -128 to – 127
unsigned 1 0 to 265
signed char 1 -128 to 127
int 2 -32768 to 32768
unsigned int 2 0 to 65535
signed int 2 -32768 to 32768
short int 2 -32768 to 32768
long int 4 -2147483648 to 2147483648
signed long int 4 -2147483648 to 2147483648
unsigned long int 4 0 to 4294967295
float 4 3.4E-38 to 3.4E+38
double 8 1.7E -308 to 1.7E +308
long double 10 3.4E-4932 to 1.1E+ 4932
Void data type
Normally used for:
• Specifying return type of function
• To indicate an empty argument list to a function
Example :
void function(void);
• Used in the declaration of generic pointer
Example :
void *gp;
Note: it is allowed in C but not in C++. But cast operator can be used for this purpose.

void *ptr1; ptr2=(char * ) ptr1;


void *ptr2;
Need of cast operator in C++
Allowed in C
User Defined Data Types:
Structures and Classes
• User defined types such as struct and union in C provides us
with more functionality of defining custom data types and
allow grouping multiple variables into a single unit
• C++ permits us to define another user defined data type
known as class
• Class variables are also known as objects which is the central
focus of OOPS
User Defined Data Types:
Enumerated Data Type
• Is another user defined data type which consist of named
constants called enumerators
• It provides a way to define a list of named values that
represent mutually exclusive choices
• Example:
enum shape { circle,square,triangle}
enum colour{red,blue,green,yellow}
enum position {off,on}
User Defined Data Types:
• C defines the types of enums to be ints. In C++,each enumerated data type retains its own
separate type. This means that C++ does not allow an int value to be automatically converted
to an enum.
• Example:
colour background =blue; //vaid
colour background =7; //error in c++
colour background =(colour) 7;//ok

• By default, the enumerators are assigned integer values starting with 0


• We can also write
enum color {red, blue=4,green=8};
enum color {red=5,blue,green};
Reference Variables
• C++ introduces a new kind of variable known as the reference variable. A
references variable provides an alias.(alternative name) for a previously
defined variable.
• For example ,if we make the variable sum a reference to the variable total,
then sum and total can be used interchangeably to represent the variable.
• A reference variable is created as follows:

• Synatx:
Datatype & reference_name=variable_name;

• Eg : int originalVariable = 23;


int& referenceVariable = originalVariable;

Note : A reference variable must be initialized at the time of declaration .


Derived Data Types
• Arrays
– Same as in c expect for the character arrays
– In C, the compiler allow us to declare the array
size as the exact length of the string constant
char string[3] = “abc”;
– But in C++ the size should be one larger than the
number of characters in string
char string[4] = “abc”;
• Pointers
– They are declared and initialized as in C
int* ptr; // integer pointer
ptr = &x; // address of x assigned to ptr
*ptr = 5; // 5 assigned to x

• Functions
– Functions are more advanced in C++ according to needs
of OOP
– Some concepts like function overloading, inline
functions, etc. have been introduced
Operators in C++
• C++ has a rich set of operators. All C operators are valid in C++ also. In
addition. C++ introduces some new operators.

<< Insertion operator


>> Extraction operator
:: Scope resolution operator
::* Pointer to member declarator
* Pointer to member operator
.* Pointer to member operator
Delete Memory release operator
Endl Line feed operator
New Memory allocation operator
Setw Field width operator
Scope Resolution Operator
• Like C,C++ is also a block-structured language. Same variables can be
declared in different blocks because the variables declared in blocks are
local to that function.
• Blocks in C++ are often nested.
• Block 2 is contained in block 1 .Note that declaration in an
inner block hides a declaration of the same variable in an
outer block and therefore each declaration of x causes it to
refer to a different data object .
• Within the inner block the variable x will refer to the data
object declared there in.
• In C, the global version of a variable can't be accessed from
with in the inner block.
• C++ resolves this problem by introducing a new operator ::
called the scope resolution operator .This can be used to
uncover a hidden variable.
• Syntax:
: : variable_name;
Pointer to Member Declarator
Memory Management Operator
• C uses malloc and calloc functions to allocate memory dynamically at run
time.
• Similarly it uses the functions free() to free dynamically allocated memory.
• We use dynamic allocation techniques when it is not known in advance
how much of memory space as needed.
• C++ also support those functions
• It also defines two unary operators new and delete that perform the task
of allocating and freeing the memory in a better and easier way
• The new operator can be used to create objects of any type.
• Syntax: pointer-variable =new datatype;
• Example :
Normal declaration/initialization : int a = 10;
Using new keyword : int* a = new int; // allocated 2 bytes memory
Using new for array : int* a = new [50]; // allocates 100 bytes memory
Using new for class : Employee* e = new Employee();

• Syntax: delete pointer-variable;


• Example:
delete a;
delete e;
Manipulators
• Manipulators are operator that are used to
format the data display. The most commonly
manipulators are endl and setw.
• The endl manipulator, when used in an output
statement, causes a line feed to be insert.(just
like \n)
• Example:
cout << "m=" << m << endl;
cout << "n=" << n << endl;
cout << "p=" << p << endl;
• If we want to print all numbers in right
justified way use setw which specify a
common field width for all the nos.
• Example:
cout<<setw(5)<<a<<endl;
cout<<setw(10)<<”b”<<setw(10)<<b<<endl;
cout<<setw(10)<<”c”<<setw(10)<<c<<endl;
cout<<setw(10)<<”total=”<<setw(10)<<total;
Output
Control Structures
• The if statement
– Simple if statement
– If..else statement
• The switch statement
– This is a multiple-branching statement where, based on a condition, the control is transferred to one
of the many possible condition

switch(expr)
{
case 1:
action1;
break;
case 2:
action2;
break;
..
..
default:
message
}
• The while statement

while(condition)
{
statements
}
• The do-while statement

do
{
statements;
} while(condition);
• For loop

for(initialization;condition;incr/decr)
{
Statements;
Statements;
}
Constants
• Is a value that cannot be changed during execution of program
• Creating constants
 Using const keyword
 const int MAX_VALUE = 30;
 const double PI = 3.14;
 Using the #define preprocessor directive
 #define MAX_VALUE 30
 #define PI 3.14
 Enumerations
 enum Color{
 RED,
 GREEN,
 BLUE
 };
Constants
• const variables have scope just like any other variables limited to
functions, classes, etc.
• const variables are stored in memory while on the other hand #define
constants are just textual replacement, they are substituted directly during
preprocessing stage and doesn’t involve memory allocation
• const are evaluated at compile time whereas #define are evaluated by the
preprocessor at preprocessing time which occurs before the compilation
• Note : #define directives are also called symbolic constants
Strings
• String is an array of characters or alphabet
• Strings may be alphabet, digits or special characters written in double quotation
• It is a class in C++ that is a part of standard library to handle string manipulation
• Some examples include:
• std::string strOne(5, ‘A’) // initialization with repeated characters
• std::cout << “Hello”
• std::cin >> variable_name
• string1 + “,” + string2
• str.length()
• str.at(1)
• str1 == str2
• str1.compare(str2)
Type Conversion
• Type conversion or type casting refers to changing entity of one datatype to
another
• There are two types of conversion that is implicit and explicit conversion
• This is primarily used to perform calculations more effectively
• Implicit Conversion
• This conversion happens automatically by the compiler when it is safe and doesn’t
result is data loss. For example, conversion from int to float or assigning a smaller
integer type to a larger integer type
• Example :
• int x =5 ;
• float y = x; // implicit conversion
• Explicit Conversion
• This conversion is performed explicitly by the programmer using casting operators

Type Conversion (cont..)
• Explicit type conversion can be done in two ways:
 Converting by assignment
 Done by explicitly defining the required type in front of the expression in
parenthesis. It is also called forceful conversion.
 Syntax : (type) expression
 Example :
 int m = 5;
 float y = (float) m/2;
 If we don’t provide float before expression m/2 then we get only 2 which is not
the exact output.
 Conversion by cast operator
 Cast operator is a special operator that forces one data type to be converted into
another.


Type Conversion (cont..)
• The most general cast operators supported by C++ compilers are:
• Static Cast
 It is used to perform compile time type conversion between compatible types
 It is safer alternative since conversions are done by compiler if it is safe
 Syntax : static_cast<new_data_type> (expression)
 Example : int x = 5; double y = static_cast<double>(x);
 Dynamic Cast
 It is used for performing dynamic type conversions between pointers to classes in
inheritance
 It checks conversion is valid or not at runtime
 Returns a pointer of target type if conversion is success and returns null if not
 Syntax : dynamic_cast<new_type> (expression)


Type Conversion (cont..)
• Const Cast
• Used to add or remove ‘const’ qualifier from a variable, pointer or reference
• Used when we need to modify an object that is originally declared as ‘const’
• Syntax : const_cast<new_type> (expression)
• Reinterpret Cast
• Used to perform low level reinterpretation of one type to another type.
• Allows to reinterpret the binary representation of an object as a different type
even if the type are unrelated
• It is powerful and considered as unsafe and only used when absolutely necessary
• Syntax : reinterpret_cast<new_type> (expression)
Function Overloading
• Two or more functions having same name but different arguments are known as
overloaded functions and this mechanism used in program is called function
overloading
• Example:
• int test(){ }
• int test(int a){ }
• int test(double a){ }
• int test(int a, double a){ }
• Note : return type can be same but arguments must be different
• Example :
• ​// gives error
• int test(int a){ }
• double test (int b) { }
Function Overloading (cont..)
Inline Functions
• They are the C++ enhancement feature to increase the execution time of a
program.
• Functions can be instructed to compiler to make them inline so that compiler can
replace those function definition wherever those are being called.
• Compiler replaces the definition of inline functions at compile time instead of
referring at runtime
• “inline” keyword is used in normal function to make it inline
• Syntax :
• inline return_type function_name(parameters)
• {
 // code
• }
• Note : It is only applicable for small functions. If the function is big then, compiler
can ignore the “inline” request and treat as a normal function.
Inline Functions
Inline Functions
• Advantages
• Less overhead of function call and return
• Saves the overhead of push/pop variables on the stack when function is called.
• Reduction in final executable code size

• Disadvantages
• If too many functions are used then size of executable file will be large because of
duplication of same code
• Too much inlining may reduce the speed of instruction fetch from cache memory
to the primary memory
• Not useful in embedded systems because code size is more important than speed
in embedded systems
• Inline function can cause thrashing because it can increase the size of binary
executable file. Thrashing causes performance degrade of a computer.
Default Arguments
• A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the caller of the function doesn’t provide
a value for the argument with a default value.
• If user doesn’t supply value then default value will be used, if the user supply the
value then user supplied value is used.
• Example :
• int add (int x=5,int y=6)
Call by reference/Pass by reference
• There may arise a situation where we would like to change the values of variables
in the calling program using function which is not possible if the call by value
method is used.
• This is because the function doesn’t have access to the actual variables in the
calling program and can only work on the copy of the values.
• Call by reference works fine if the function does not need to alter the values of the
original variables in the program.
• In call by value, original value is not modified
Call by value example
Call by reference/Pass by reference
• In call by reference original value is modified because we pass reference (address)
• Here address of the value is passed in the function, so actual and formal
arguments share the same address space
• Hence value changed inside the function is also reflected outside the function
Errors and Warnings
• Compile Time Errors
• Runtime Errors
• Warnings

You might also like