Posts

Showing posts with the label Function

What is Return by Reference in C++

What is Return by Reference in C++ In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference. To understand this feature, you should have the knowledge of: Global variables Example: Return by Reference #include <iostream> using namespace std ; // Global variable int num ; // Function declaration int & test (); int main () { test () = 5 ; cout << num ; return 0 ; } int & test () { return num ; } Output 5 In program above, the return type of function  test()  is  int& . Hence, this function returns a reference of the variable  num . The return statement is  return num; . Unlike return by value, this statement doesn't return value of  num , instead it returns the variable itself (address). So, when the  variable  is returned, it can be assigned a value as done in ...

C++ Recursion(How recursion works in C++)

Image
C++ Recursion(How recursion works in C++) A function that calls itself is known as recursive function. And, this technique is known as recursion. How recursion works in C++? void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... } The figure below shows how recursion works by calling itself over and over again. The recursion continues until some condition is met. To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call and other doesn't. Example 1: Factorial of a Number Using Recursion // Factorial of n = 1*2*3*...*n #include <iostream> using namespace std ; int factorial ( int ); int main () { int n ; cout << "Enter a number to find factorial: " ; cin >> n ; cout << "Factorial of " << n << " = " << facto...

Storage Class in C++

Image
Storage Class in C++ Every variable in C++ has two features: type and storage class. Type specifies the type of data that can be stored in a variable. For example:  int ,  float ,  char  etc. And, storage class controls two different properties of a variable: lifetime (determines how long a variable can exist) and scope (determines which part of the program can access it). Local Variable A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable. Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function. The life of a local variable ends (It is destroyed) when the function exits. Example 1: Local variable #include <iostream> using namespace std ; void test (); int main () { // local variable to main() int var = 5 ; ...