Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Calling a function multiple times retains values of local variables . why?

0 votes
asked Mar 3, 2021 by mfahadshah (130 points)
#include <iostream>

using namespace std;
void fun ();
int main ()
{
  int n;
  cout << n << endl;

  //for(int i=1;i<=5;i++) //calling the function using loop gives same results

             //fun ();

//as these lines (calling them in each line)

 fun ();
  fun ();
  fun ();

  cout << n << endl;
  return 0;
}

void
fun ()
{
  int n;
  n++;
  cout << "n=" << n << endl;
}

output:

0
n=32719
n=32720
n=32721
0

my question is why the value of n increments as it is local variable. and it is not incremented if i print anything else between function calls.

1 Answer

0 votes
answered Mar 13, 2021 by xDELLx (10,500 points)
In c/c++ always make sure to give inital value to variable.

failing to initialise variable & using them directly will have garbage values.The incrementing you see is a side effect of accessing uninitialised variable.

try setting n to 0 & see what results you get.
commented Mar 24, 2021 by mfahadshah (130 points)
thanks for your reply.. i know initialization is important but my question is about the weird behavior i get if i call the function 3 times in a row i get incremented values for uninitialized variable but if i print something in between then incrementing stops. please check example below:
 fun ();
cout<<"Hello"<<endl;
  fun ();
cout<<"Hello"<<endl;
  fun ();

Output:
n=32719
Hello
n=32719
Hello
n=32719
commented Mar 24, 2021 by xDELLx (10,500 points)
this "wierd" behavior is the famous undefined behavior of c/c++.
if you want to check the exact reason why you see this output it would help to check the assembly code generatedc by compilers.
Also its not guaranteed all compilers would show same results.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...