-
For loop problem
Hello :)
So this code does compile successfully, but outputs nonsense.
Code:
int f( string str )
{
for(int a ; a<5 ; a++)
{
cout << a;
}
}
int main()
{
cout << f("a");
cin.get();
}
The output I get is
2293536
Shouldn't this normally output the numbers zero through four and return nothing?
Thanks :)
-
You failed to initialise a to 0. As for the return value: there is undefined behaviour, since the function does not actually return a value, yet you attempt to use that return value.
-
Haha how silly of me.
Thanks :)
-
Also, the function should be of type void (as you don't return anything), and also does not need to take any argument in this instance.
It should have been written as such:
Code:
void f( )
{
for(int a = 0 ; a<5 ; a++)
{
cout << a;
}
}
int main()
{
f();
cin.get();
}
-
True, I am aware of the void datatype. The function in my actual program does return a value and takes a string as input. I was just writing an example and didn't bother removing them since I knew the lack of a return value and the string argument weren't the causes of the problem.