Unit 2 Basics of C Programming
Unit 2 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
• Synatx:
Datatype & reference_name=variable_name;
• 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.
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