Hi there I've got a problem with functions, where it seems that function call return zero instead of the actual variable value, I will appreciate any help from you guys.
I will post the major code parts because the program is big.
I get the totallength variable value right but for t i get zero istead of 1, 2, 3, ...
did I miss something here??

using namespace std;
//global variables
    int t;
    static float totallength=0;

// the function 
void FileOutput(int a, float b)
{
ofstream outData("Output1.csv", std::ios::out | std::ios::app);
if (outData.good())
{
    cout<<t<<totallength<<endl;
    outData << t <<","<<totallength<<endl; //writing
    cout<<endl;
}
outData.close();
}


int main()
{
  for (int t=0;t<20;t++) { 
.
.
.
.
FileOutput(t,totallength);
}
.
.
return 0;
}

Recommended Answers

All 5 Replies

did I miss something here??

There are too many variables named t. There's the global t and the local t in main()'s loop. It's recommended not to use the same name more than once for nested scopes. It's very easy to get confused.

You have a global variable named t, and a variable t in your for loop, inside the FileOutput() function the loop counter variable t is referred to as a (its name inside the function as you specified) so when you do cout<<t<<totallength<<endl; you are using the global value t which is default initialised to 0.

hmm.. but when I decalred t only in the function I kept getting this irrelevent value which is 4722728 >.<

Local variables in functions usually just get any old trash that was in ram at the time. Id you want to print t, from your loop passed to the function you must use the name you have given it inside the function.

thanks alot Kanoisa and deceptikon it worked fine after I replaced t by a in the function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.