Lecture 2
Lecture 2
Paradigms in C++
CSCI 3142
By
Priyanka Samanta
Const Qualifier in C++
Definition of const:
• part of data type
• const object can never be modified
• Some code promises not to change anything
• const int is same as int with an additional restriction declaring the value of the int can
not be changed.
Example: A variable to refer to the size of a buffer size
Examples of const
const int buffsize=256; // input buffsize is a named const
(Note: Any attempt to assign to buffsize is an error!)
buffSize=512; //Error
Initialization: Because we can’t change the value of a const object after we create it, it must be initialized.
int a=21;
const int ci=a; // ok: the value in a is copied into ci
Under the new standard we can ask the compiler to verify that a variable is a constant
expression by declaring the variable in a constexpr declaration.
Variables declared as constexpr are implicitly const and must be initialized by constant
expressions.
Examples
constexpr int mf=20; //20 is a constant expression
constexpr int limit=mf+1; // mf+1 is a constant expression
constexpr int sz=size(); // ok only if size is a constexpr function
Best practices: Generally, it is a good idea to use a constexpr for variables that you
intend to use as constant expression.
Examples
• const int dmv=17; // dmv is a named const
• int var=17; //var is not const
• constexpr double max1=1.4*square(dmv); //ok, as square(17) is a constant
expression
• constexpr double max2=1.4*square(var); //error, var is not a const
expression
• const double max3=1.4*square(var); //ok, maybe evaluated at run time
Rules for constexpr function
• To be constexpr, a function must rather be simple; just a return statement computing a value.
• A constexpr function can use non-const argument.
Example: When we write y=add(5,8), it does not need to be evaluated at run time as we are not
waiting for user given arguments. This can be run during compile time!
But constexpr function can be called both compile time and run time.
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-constexptr#constexpr.cpp
Enum and Typedef
Enum is related set of values or constants under one name, and it is user defined datatype. It is useful to when
you want to use integers to represent certain states, also give them certain name for readability purpose!
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-constexptr#enum.cpp
Logical operators
What is the difference between the following two statements?
• if (hours>=9 && hours<=18) //checks if both are true
• if (age>=12, age<=50) //True if the second condition is true
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-
constexptr#logical_operator.cpp
Nested if-else in C++
Example: Find the maximum of 3 numbers
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-
constexptr#find_max.cpp
Short circuit
• if (a>b && a>c) // a=3, b=5; second condition will not be checked
• if (a>b || a>c) // a=5, b=3; second condition will not be checked
• What will be the output of the following code?
int a=5, b=7, i=5;
if (a>b && ++i<b)
cout<<i;
• What will be the output if a=15?
• What will be the output of the following code?
int a=5, b=7, i=5;
if (a>b || ++i<b)
cout<<i;
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-constexptr#short_circuit.cpp
Dynamic declaration
In dynamic declaration, the initial value of the variable is the result of an expression or
the return value of a method call. Dynamic declaration happens at runtime.
int main(){
int a=10, b=5; //static declaration
if(true){
int c=a+b; //dynamic declaration
cout<<c<<endl;
}
int d = Math.sqrt(a); //dynamic declaration
cout<<c<<endl; //Error: use of undeclared variable
}
Loops
• While loop
• do-while loop
• for loop
• for-each loop (will explain later while covering arrays)
While and do-while loop
Code: https://replit.com/@SamantaPriyanka/Enum-
typedef-constexptr#do_while_loop.cpp
for loop
Code: https://replit.com/@SamantaPriyanka/Enum-
typedef-constexptr#for_loop.cpp
Switch case
switch(expr)
{ case 1:………………..
break;
case 2:………………..
break;
default: ……………..
}
Fall through condition : If you do not put a break, then both the cases will be executed.
Sometimes it can be advantageous too.
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-constexptr#switch_case.cpp
Fall through code: https://replit.com/@SamantaPriyanka/Enum-typedef-
constexptr#switch_case2.cpp
Practice
Write a C++ Program using switch statement.
* To input a Month Number from user using cin.
* This C++ program then displays the number of days in this month.
* If number is not between 1 and 12 then program will display “Invalid Month
Number message”
Arrays
• Why we need an array?
• An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique
identifier.
NOTE: The elements field within square brackets [], representing the number of
elements in the array, must be a constant expression, since arrays are blocks of static
memory whose size must be determined at compile time, before the program runs.
Initializing arrays
• int foo [5] = { 16, 2, 77, 40, 12071 };
• The number of values between braces {} shall not be greater than the
number of elements in the array.
• If declared with less, the remaining elements are set to their default values
(which for fundamental types, means they are filled with zeroes)
int bar [5] = { 10, 20, 30 }; // allowed
• The initializer can even have no values, just the braces: int baz [5] = { };
Initializing arrays
• When an initialization of values is provided for an array, C++ allows the
possibility of leaving the square brackets empty []. In this case, the
compiler will assume automatically a size for the array that matches the
number of values included between the braces {}:
int foo [] = { 16, 2, 77, 40, 12071 };
• Finally, the evolution of C++ has led to the adoption of universal
initialization also for arrays. Therefore, there is no longer need for the equal
sign between the declaration and the initializer. Both these statements are
equivalent:
int foo[] = { 10, 20, 30 };
int foo[] { 10, 20, 30 };
Accessing the values of an array
• Syntax: name[index]
• foo [2] = 75;
• For copying value: x = foo[2]; //x will be of type int
• In C++, array index always starts from 0.
• In C++, accessing out-of-range elements do not cause errors on
compilation, but can cause errors on runtime.
• Do not confuse these two possible uses of brackets [] with arrays.
int foo[5]; // declaration of a new array
foo[2] = 75; // access to an element of the array.
Accessing array elements using loop
• Using simple for loop
• Using for-each loop
• Code: https://replit.com/@SamantaPriyanka/Enum-typedef-
constexptr#Array_element_access.cpp
Pratice
Write a C++ Program to find max number from an array.
* To input 10 integers from user and store them in an array.
* Display the array elements entered by the user using for-each loop.
* This C++ program then finds and display the max number from the array.
Multi-dimensional array
• Multidimensional arrays can be described as "arrays of arrays". For
example, a bidimensional array can be imagined as a two-dimensional table
made of elements, all of them of a same uniform data type.
Code: https://replit.com/@SamantaPriyanka/Enum-typedef-
constexptr#multidimensional_array.cpp
Homework
Write a C++ Program to create user defined 2D array using for loop.
* Ask user to input rows and col numbers for a 2D array.
* Declare an 2D array Arr[row][col].
* Take input from user to initialize the array using nested for loop
* Display the array elements entered by the user using nested for loop.