Using constant argument/parameter in a function
Writing a program to find student division using the const argument for maximum marks.
Learning Objectives
- Using const as argument or parameter in a function.
- Learning to use many return paths in the function definition.
Source Code
|
|
Run Output
Code Understanding
int MM=50; //This is the maximum marks we fix in the calling function
int marks; cout<<“Enter marks out of “<<MM<<” : “; cin>>marks;
Here we will collect the student marks.
int div=division(MM,marks);
Here we are calling the function to find the division of the student using MM and marks as the parameter. Before passing we may change the value of MM, but within the function it can not be changed.
cout<<“Student division = “;
switch(div) { case 1:cout<<“First”; break;
case 2:cout<<“Second”; break;
case 3:cout<<“Third”; break;
case 0:cout<<“Did not Qualify”; }
With this code we print the student division based on integer value returned from the called function using a switch case.
int division(const int mm,int m)
This is the function definition header where the mm variable which the first variable has been added with a modifier const so that inside this function it can not be modified. This is also called setting a variable type to read only type. The second parameter is the marks obtained by the student.
{ float p=(float (m)/mm)*100; if(p >=60) return 1; else if(p >=45) return 2;
else if(p >=33) return 3; else return 0; }
Here the logic of percentage calculation and then return the value based on marks has been written in the function body. Watch that there are many return paths in this function.
Notes
- If there are many return paths in a function the programmer is responsible for ensuring that on any typical value some return root is available. If it is not so you may get compiler warning or the function may fail at run time on certain values inputs.
- At the time of prototype making if const modifier is not given, even then the const modifier can be given at the time of writing the function definition.
Suggested Filename(s): fn-const-param.cpp
Created: 5-Jan-2018 22:05 | Updated: 15-Sep-2018 14:08|
