Functions On C++-1
Functions On C++-1
Table of content:.........................................................................................................................................1
C++ functions...............................................................................................................................................1
Library Function...........................................................................................................................................1
User-defined Function.................................................................................................................................2
Function prototype(declaration).................................................................................................................4
Function Call................................................................................................................................................4
Passing Arguments to Function...................................................................................................................5
C++ User-defined Function Types.....................................................................................................6
1) Function with no argument and no return value................................................................7
2) Function with no arguments but return value.....................................................................7
3) Function with argument but no return value.......................................................................8
4) Function with arguments and return value..........................................................................9
Function overloading.............................................................................................................................9
Example 1: Function Overloading............................................................................................10
Example 2: Function Overloading............................................................................................11
C++ Storage Class.......................................................................................................................................12
Static Local variable...................................................................................................................................14
C++ Recursion......................................................................................................................................15
Example 1: C++ Recursion............................................................................................................15
Passing values in C++...........................................................................................................................18
1. Call by reference (pass values by reference)...............................................................................18
Example 1: Return by Reference.................................................................................................18
Important Things to Care While Returning by Reference.................................................19
call by reference..............................................................................................................................20
Using const.......................................................................................................................................20
Call by value....................................................................................................................................20
Simple functions................................................................................................................................21
Call by value....................................................................................................................................21
C++ Arrays.............................................................................................................................................21
Defining Arrays.................................................................................................................................21
Array Elements.................................................................................................................................22
Array Initialization.................................................................................................................................22
Example 1: C++ Array.....................................................................................................................23
C++ Multidimensional Arrays............................................................................................................24
Multidimensional Array Initialization...........................................................................................24
Initialization of three dimensional array.................................................................................25
Example 1: Two Dimensional Array........................................................................................25
Example 2: Two Dimensional Array............................................................................................26
Example 3: Three Dimensional Array.....................................................................................27
Passing Array to a Function in C++ Programming......................................................................................29
Passing Multidimensional Array to a Function.........................................................................31
Example 2: Passing Multidimensional Array to a Function..................................................31
C++ Program to display the elements of two dimensional array by passing it to a
function..............................................................................................................................................31
C++ Strings............................................................................................................................................32
C-strings.............................................................................................................................................32
Example 1: C++ String....................................................................................................................33
Example 2: C++ String....................................................................................................................34
Passing String to a Function.........................................................................................................34
C++ Structures......................................................................................................................................35
How to define a structure in C++ programming?.....................................................................35
How to define a structure variable?............................................................................................36
How to access members of a structure?...................................................................................36
Example 1: C++ Structure..............................................................................................................36
C++ Structure and Function..............................................................................................................37
Passing structure to function in C++...........................................................................................37
Example 1: C++ Structure and Function................................................................................38
Returning structure from function in C++..................................................................................39
C++ Pointers to Structure..................................................................................................................40
Example 1: Pointers to Structure.................................................................................................40
C++ Enumeration.................................................................................................................................42
Example 1: C++ Enumeration.......................................................................................................42
Example 2: C++ Enumeration.......................................................................................................43
C++ functions
In programming, function refers to a segment that groups codes to perform a specific task. Depending
on whether a function is predefined or created by programmer; there are two types of function:
1. Library Function
2. User-defined Function
Library Function
Library functions are the built-in function in C++ programming. Programmer can use library function by
invoking function directly; they don't need to write it themselves.
# include <iostream>
#include <cmath>
int main() {
cin>>number;
squareRoot = sqrt(number);
return 0;
}
Output
Enter a number: 26
In example above, sqrt() library function is invoked to calculate the square root of a number. Notice
code #include <cmath> in the above program. Here, cmath is a header file. The function definition
of sqrt()(body of that function) is written in that file. You can use all functions defined in cmath when
you include the content of file cmath in this program using #include <cmath> .
Every valid C++ program has at least one function, that is, main() function.
User-defined Function
C++ allows programmer to define their own function. A user-defined function groups code to perform a
specific task and that group of code is given a name(identifier). When that function is invoked from any
part of program, it all executes the codes defined in the body of function.
Consider the figure above. When a program begins running, the system calls the main() function, that is,
the system starts executing codes from main() function. When control of program reaches
to function_name() inside main(), the control of program moves to void function_name(), all codes
inside void function_name() is executed and control of program moves to code right
after function_name() inside main() as shown in figure above.
Example 1: Function
C++ program to add two integers. Make a function add() to add integers and display sum in main()
function.
# include <iostream>
int main() {
cin>>num1>>num2;
cout<<"Sum = "<<sum;
return 0;
int add;
add = a+b;
Output
-4
Sum = 4
Function prototype(declaration)
If an user-defined function is defined after main() function, compiler will show error. It is because
compiler is unaware of user-defined function, types of argument passed to function and return type.
In C++, function prototype is a declaration of function without function body to give compiler
information about user-defined function. Function prototype in above example:
You can see that, there is no body of function in prototype. Also there are only return type of arguments
but no arguments. You can also declare function prototype as below but it's not necessary to write
arguments.
Function Call
To execute the codes of function body, the user-defined function needs to be invoked(called). In the
above program, add(num1,num2); inside main() function calls the user-defined function. In the above
program, user-defined function returns an integer which is stored in variable add.
Function Definition
The function itself is referred as function definition. Function definition in the above program:
/* Function definition */
int add;
add = a+b;
When the function is called, control is transferred to first statement of function body. Then, other
statements in function body are executed sequentially. When all codes inside function definition is
executed, control of program moves to the calling program.
Passing Arguments to Function
In programming, argument (parameter) refers to data this is passed to function(function definition)
while calling function.
In above example, two variables, num1 and num2 are passed to function during function call. These
arguments are known as actual arguments. The value of num1 and num2 are initialized to
variables a and b respectively. These arguments a and b are called formal arguments. This is
demonstrated in figure below:
The numbers of actual arguments and formals argument should be same. (Exception: Function
Overloading)
The type of first actual argument should match the type of first formal argument. Similarly, type
of second actual argument should match the type of second formal argument and so on.
You may call function without passing any argument. The number(s) of argument passed to a
function depends on how programmer want to solve the problem.
In above program, both arguments are of int type. But it's not necessary to have both
arguments of same type.
Return Statement
A function can return single value to the calling program using return statement. In the above program,
the value of add is returned from user-defined function to the calling program using statement below:
return add;
In the above program, the value of add inside user-defined function is returned to the calling function.
The value is then stored to a variable sum. Notice that, the variable returned, that is, add is of
type int and also sum is of int type. Also notice that, the return type of a function is defined in function
declarator int add(int a,int b). The int before add(int a,int b) means that function should return a value
of type int. If no value is returned to the calling function then, void should be used
For better understanding of arguments and return in functions, user-defined functions can
be categorised as:
Consider a situation in which you have to check prime number. This problem is solved below by making
user-defined function in 4 different ways as mentioned above.
1) Function with no argument and no return
value
# include <iostream>
using namespace std;
void prime();
int main() {
prime(); // No argument is passed to prime().
return 0;
}
int prime();
int main() {
int num, i, flag = 0;
num = prime(); /* No argument is passed to prime() */
for (i = 2; i <= num/2; ++i) {
if (num%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
return 0;
}
int main() {
int num;
cout<<"Enter a positive integer to check: ";
cin>>num;
// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n) {
int i, flag = 0;
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<n<<" is not a prime number.";
}
else {
cout<<n<<" is a prime number.";
}
}
4)Function with arguments and return value.
#include <iostream>
using namespace std;
int main() {
int num, flag = 0;
cout<<"Enter positive enter to check: ";
cin>>num;
flag = prime(num); /* Argument num is passed to check() function. */
if(flag == 1)
cout<<num<<" is not a prime number.";
else
cout<<num<<" is a prime number.";
return 0;
}
Function overloading
In C++ programming, two functions can have same identifier(name) if either number of arguments or
type of arguments passed to functions are different. These types of functions having similar name are
called overloaded functions.
int test() { }
#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;
test(a);
test(b);
test(a, b);
return 0;
}
Output
Integer number: 5
In above example, function test() is called with integer argument at first. Then, function test() is called
with floating point argument and finally it is called using two arguments of type int and float. Although
the return type of all these functions is same, that is, void, it's not mandatory to have same return type
for all overloaded functions. This can be demonstrated by example below.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
Output
Absolute value of -5 = 5
In above example, two functions absolute() are overloaded. Both take single argument but one takes
integer type argument and other takes floating point type argument. Function absolute() calculates the
absolute value of argument passed and returns it.
Local variable
Global variable
Static local variable
Local Variable
A variable defined inside a function (defined inside function body between braces) is a local variable.
Local variables are created when the function containing local variable is called and destroyed when that
function returns. Local variables can only be accessed from inside a function in which it exists. Consider
this example:
#include <iostream>
using namespace std;
void test();
int main() {
int var = 5; // local variable to main()
test();
var1 = 9; // illegal: var1 not visible inside main()
}
void test() {
int var1; // local variable to test()
var1 = 6;
cout<<var; // illegal: var not visible inside test()
}
The variable var cannot be used inside test() and var1 cannot be used inside main() function.
Keyword auto could also be used for defining local variables (it was optional but not necessary) before
as: auto int var; but, after C++11 auto has different meaning and should not be used for defining local
variables as variables defined inside a function is a local variable by default.
Global Variable
If a variable is defined outside any function, then that variable is called a global variable. Any part of
program after global variable declaration can access global variable. If a global variable is defined at the
beginning of the listing, global variable is visible to all functions. Consider this example:
#include <iostream>
using namespace std;
int c = 12;
void test();
int main() {
++c;
cout<<c<<endl; //Output: 13
test();
return 0;
}
void test() {
++c;
cout<<c; //Output: 14
}
In the above program, c is a global variable. This variable is visible to both functions in the above
program.
The memory for global variable is set when program starts and exist until program ends.
Keyword static is used for specifying static variable. For example:
... .. ...
int main() {
static float a;
... .. ...
A static local variable exist only inside a function in which it is declared(similar to local variable) but the
lifetime of static variable starts when the function containing static variable is called and ends when the
program ends. The main difference between local variable and static variable is that, the value of static
variable persist until the program ends. Consider this example:
#include <iostream>
using namespace std;
void test() {
static int var = 0; // var is a static variable;
++var;
cout<<var<<endl;
}
int main() {
test();
test();
return 0;
}
Output
In the above program, test() function is invoked 3 times. During first call, variable var is declared as static
variable and initialized to 0. Then 1 is added to var which is displayed in the screen. When the function
test() returns, variable var still exist because it is a static variable. During second function call, no new
variable var is created. Only var is increased by 1 and then displayed to the screen.
Output of above program if var was not specified as static variable
1
C++ Recursion
In many programming languages including C++, it is possible to call a function from a same function. This
function is known as recursive function and this programming technique is known as recursion.
In recursion, a function calls itself but you shouldn't assume these two functions are same function.
They are different functions although they have same name.
Local variables: Local variables are variables defined inside a function and has scope only inside that
function. In recursion, a function call itself but these two functions are different functions (You can
imagine these functions are function1 and function 2. The local variables inside function1 and function2
are also different and can only be accessed within that function.
int factorial(int);
int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}
int factorial(int n) {
if (n>1) {
return n*factorial(n-1);
}
else {
return 1;
}
}
Output
Factorial of 4 = 24
Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:
In first factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls second factorial() function and argument passed
is num-1 which is 3.
In second factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls third factorial() function and argument passed
is num-1 which is 2.
In third factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls fourth factorial() function and argument passed
is num-1 which is 1.
The fourth factorial() function, test expression inside if statement is false. The statement return
1; is executed, which returns 1 to third factorial() function.
The thrid factorial() function returns 2 to second factorial() function.
The second factorial() function returns 6 to first factorial() function.
Finally, first factorial() function returns 24 to the main() function and is displayed.
The following are two main ways in which functions receive their values
1. Call by reference -
2. Call by value-
int main() {
test() = 5;
cout<<n;
return 0;
}
int& test() {
return n;
}
Output
Explanation
In program above, the return type of function test() is int& . Hence this function returns by
reference. The return statement is return n; but unlike return by value. This statement doesn't
return value of n , instead it returns variable n itself.
Then the variable n is assigned to the left side of code test() = 5; and value of n is displayed.
int n = 2;
return n;
Ordinary function returns value but this function doesn't. Hence, you can't return constant from this
function.
int& test() {
return 2;
Example 2
call by reference
number=number*3;
return number;
int main() {
i=7;
int j = triple(i)
Here number is a sort of alias for main's i. After the call to triple, main's i will be 21, and so will j.
Using const
The const keyword can be used in several ways to prevent values being changed. For example, were
the previous example's triple changed to the following, the code wouldn't compile, because number can't
be changed.
number=number*3;
return number;
}
NB:. By careful use of const you can make your code safer, ensuring that variables that shouldn't
change are protected from accidental modification.
Call by value
In call by value, original value can not be changed or modified. In call by value, when you
passed value to the function it is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only
but it not change the value of variable inside the caller function such as main().
Simple functions
Here's a simple function which given an integer returns 3 times that integer
Call by value
number=number*3;
return number;
int main() {
i=7;
int j = triple(i)
i is "passed by value", meaning that number is initially given the value that i has, but after that there's
no connection between the variables. At the end i will be 7 and j will be 21.
Difference between call by value and call by reference.
This method copy original value into This method copy address of arguments into
1
function as a arguments. function as a arguments.
Changes made to the parameter inside Changes made to the parameter affect the
2 the function have no effect on the argument. Because address is used to access the
argument. actual argument.
Actual and formal arguments will be Actual and formal arguments will be created in
3
created in different memory location same memory location
C++ Arrays
In programming, one of the frequently arising problem is to handle similar types of data. Consider this
situation: You have to store marks of more than one student depending upon the input from user. These
types of problem can be handled C++ programming(almost all programming language have arrays) using
arrays.
An array is a sequence of variable that can store value of one particular data type. For example: 15 int
type value, 105 float type value etc.
Defining Arrays
type array_name[size];
int test[85];
The above code creates an array which can hold 85 elements of int type.
Array Elements
The maximum number of elements an array can hold depends upon the size of an array. Consider this
code below:
int age[5];
Notice that the first element of an array is age[0] not age[1] . This array has 5 elements and notice
fifth is age[4] not age[5] . C++ programmer should always keep this is mind as it may differ from other
programming languages.
Array Initialization
I prefer writing size of array during array declaration because it quickly gives the information on size of
an array while help me in debugging code.
#include <iostream>
using namespace std;
int main() {
int n[5];
cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i) {
cin>>n[i];
}
Output
Enter 5 numbers: 4
-3
First number: 4
Last number: 0
C++ Multidimensional Arrays
In arrays , you learned about one dimensional array, that is, single variables specifies array. C++ allows
programmer to create array of an array known as multidimensional arrays. Consider this example:
int x[3][4];
Here, x is a two dimensional array. This array can hold 12 elements. You can think this array as table
with 3 row and each row has 4 column.
float x [2][4][3];
This array x can hold 24 elements. You can think this example as: Each 2 elements can hold 4 elements,
which makes 8 elements and each 8 elements can hold 3 elements. Hence, total number of elements
this array can hold is 24.
Better way to initialize this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};
int test[2][3][4] = {
};
int main() {
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout<< "test["<< i << "][" << ;j << "] = " << test[i][j]<<endl;
}
}
return 0;
}
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[0][2] = 9
test[1][2] = 1
#include <iostream>
using namespace std;
const int CITY = 2;
const int WEEK = 7;
int main() {
int temperature[CITY][WEEK];
cout<<"Enter all temperature for a week of first city and then second city. \n" ;
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" : ";
cin>>temperature[i][j];
}
}
cout<<"\n\nDisplaying Values:\n";
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" = "<< temperature[i][j]<<endl;
}
}
return 0;
}
Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23
Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23
Example 3: Three Dimensional Array
C++ Program to Store value entered by user in three dimensional array and display it.
#include <iostream>
using namespace std;
int main() {
int test[2][3][2]; // this array can store 12 elements
cout<<"Enter 12 values: \n";
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cin>>test[i][j][k];
}
}
}
cout<<"\nDisplaying Value stored:"<<endl;
/* Displaying the values with proper index. */
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j][k]<<endl;
}
}
}
return 0;
}
Output
Enter 12 values:
9
10
11
12
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
#include <iostream>
using namespace std;
void display(int marks[5]);
int main() {
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
Output
Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69
When an array is passed as an argument to a function, only the name of an array is used as
argument.
display(marks);
Also notice the difference while passing array as an argument rather than variable.
The argument used marks in the above code represents the memory address of first element of
array marks[5]. And the formal argument int m[5] in function declaration decays to int* m;. That's
why, although the function is manipulated in the user-defined function with different array name m[5],
the original array is manipulated. The C++ programming language handles passing array to a function in
this way to save memory and time.
Note: You need to have understanding of pointers to understand passing array to a function. Learn
more: Call by reference
#include <iostream>
using namespace std;
void display(int n[3][2]);
int main() {
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
};
display(num);
return 0;
}
void display(int n[3][2]) {
Output
Displaying Values:
3 4 9 5 7 1
Multidimensional array with dimension more than 2 can be passed in similar way as two dimensional
array.
C++ Strings
There are two types of strings commonly use in C++ programming language:
Strings that are objects of string class (The Standard C++ Library string class)
C-strings (C-style Strings)
C-strings
In C programming, only one type of string is available and this is also supported in C++ programming.
Hence it's called C-strings. C-strings are the arrays of type char terminated with null character, that is, \
0 (ASCII value of null character is 0). Consider this example:
In the above code, str is a string and it holds 4 character. Although, " C++ " has 3 character, the null
character \0 is added to the end of the string automatically.
Like arrays, it is not necessary to use all the space allocated for the string. For example:
#include <iostream>
using namespace std;
int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}
Output
Enter a string: C++
Notice that, in second example only "programming" is displayed instead of "Programming is fun". It is
because The extraction operator >> considers a space has a terminating character.
#include <iostream>
using namespace std;
int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}
Output
To read the text containing blank space, cin.get function can be used. This function takes two
arguments. First argument is the name of the string(address of first element of string) and second
argument is the maximum size of the array.
int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
display(str);
return 0;
}
Output
C++ Structures
Structure is the collection of variables of different types under a single name for better visualisation of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure
can hold data of one or more types.
struct person {
char name[50];
int age;
float salary;
};
int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure definition only
specifies that, what property a structure variable holds when it is defined.
person bill;
Here, a structure variable bill is defined which is of type structure person. When structure variable is
defined, then only the required memory is allocated by the compiler. Considering you have either 32-bit
or 64-bit system, the memory of float is 4 bytes, memory of int is 4 bytes and memory of char is 1
byte. Hence, 58 bytes of memory is allocated for structure variable bill.
bill.age = 50;
#include <iostream>
using namespace std;
struct person {
char name[50];
int age;
float salary;
};
int main() {
person p1;
return 0;
}
Output
Enter age: 27
Displaying Information.
Age: 27
Salary: 1024.4
struct person {
char name[50];
int age;
float salary;
};
int main() {
person p;
return 0;
}
Output
Enter age: 55
Enter salary: 34233.4
Displaying Information.
Age: 55
Salary: 34233.4
In this program, user is asked to enter the data for the members of a structure variable
inside main() function. Then that structure variable to passed to a function using code.
displayData(p);
The return type of displayData() is void and one argument of type structure person is passed.
The function prototype also should match the function definition. Then the members of structure p1 is
displayed from this function.
struct person {
char name[50];
int age;
float salary;
};
person getData(person);
void displayData(person);
int main() {
person p;
p = getData(p);
displayData(p);
return 0;
}
In this program, the structure variable p of type structure person is defined under main() function.
The structure variable p is passed to getData() function which takes input from user and that value is
stored in member function of structure variable p1 which is then returned to main function.
p = getData(p);
Note: The value of all members of a structure variable can be assigned to another structure using
assignment operator = if both structure variables are of same type. You don't need to manually assign
each members.
Then the structure variable p is passed to displayData() function, which displays the information.
#include <iostream>
using namespace std;
struct temp {
int i;
float f;
};
int main() {
temp *ptr;
return 0;
}
This program creates a pointer ptr of type structure temp.
Example 1: Pointers to Structure
#include <iostream>
using namespace std;
struct Distance {
int feet;
float inch;
};
int main() {
Distance *ptr, d;
ptr = &d;
return 0;
}
Output
Enter feet: 4
Displaying information.
The syntax to access member function using pointer is ugly and there is alternative
notation -> which is more common.
ptr->feet is same as (*ptr).feet
C++ Enumeration
This code is a enum declaration. After declaration, you can define variable of type seasons. And this
variable of type seasons can only have one of those 4 values. For example:
C++ program to define enumeration type and assign value to variable of that type.
#include <iostream>
using namespace std;
int main() {
seasons s;
s = autumn; // Correct
s = rainy; // Error
return 0;
}
In this program, an enum type seasons is declared with 4 enumerators
(spring, summer, autumn, winter). Then, inside main() function, a variable s of type seasons is
defined. This variable s can only store any one of four values (spring, summer, autumn, winter).
By default, the value of first enumerator is 0, second is 1 and so in. In this program, spring is equal to
0, summer is equal to 1 and autumn is 2 and winter is 3.
One very important thing to remember is that, spring, summer etc are not variables. They are treated
as integers by compiler. Hence, once enumerators are defined, their value can't be changed in program.
int main() {
seasons s;
s = spring;
cout >> "spring = " >> s >> endl;
s = summer;
cout >> "summer = " >> s >> endl;
s = autumn;
cout >> "autumn = " >> s >> endl;
s = winter;
cout >> "winter = " >> s >> endl;
return 0;
}
Output
spring = 0
summer = 1
autumn = 2
winter = 3
You can change the default value during enumeration declaration (after declaration, you cannot change
it) and give them another value. Consider this example:
int main() {
seasons s;
s = summer;
cout << "summer = " << s << endl;
return 0;
}
Output
summer = 4
In this program, the enumerations are given the different integer value than default value.