Can anybody tell me how I should fix this error? I cannot print the numbers of 10 to 19 individually.
# include <iostream>
using namespace std;
int while_loop(int a)
{
a = 10;
while (a < 20)
{
a ;
return a;
}
}
int main()
{
int a, result;
result = while_loop(a);
cout << "The result of while_loop is : " << result << endl;
return 0;
}
CodePudding user response:
The compiler is not perfect in this case:
int while_loop(int a)
{
a = 10;
while (a < 20)
{
a ;
return a;
}
}
Since you set a initially to 10, this loop will always terminate (after exactly one iteration). However, in the general case, a while loop will run multiple times or never, and that means that you need to add a return
statement after the loop.
The code you have written does not use the loop, as it always returns 11 due to the unconditional return a;
inside your loop. What you want is probably:
while (a < 20)
{
a ;
}
return a;
Also, your main function passes an uninitialized value to your loop function:
int a, result; // change that to int a = 10
result = while_loop(a);
and then you can remove the a = 10
from inside the function.
CodePudding user response:
Mistake 1
When you wrote:
int a, result;
result = while_loop(a);//UNDEFINED BEHAVIOR
The variables a
and result
have garbage value since they are of built in type(in local scope) and you haven't initialized them. And using/accessing that garbage value leads to undefined behavior. So while_loop(a)
leads to undefined behavior.
To solve this you should initialize a
to 10
as shown below.
int a =10, result;//INITIALIZED a to 10
result = while_loop(a);
Mistake 2
Inside the while_loop
function if the condition while (a < 20)
is not met then the control flow will not encounter any return
statement and so you get the mentioned warning.
To solve this you can move the return a;
outside while
loop as shown below:
int while_loop(int a)
{
//a = 10;//NO NEED FOR THIS
while (a < 20)
{
a ;
}
return a;//return moved outside while
}
Corrected Program
So the modified program looks like:
# include <iostream>
using namespace std;
int while_loop(int a)
{
//a = 10;NO NEED FOR THIS
while (a < 20)
{
a ;
}
return a;//return MOVED OUTSIDE while
}
int main()
{
int a = 10, result;//INITIALIZE a to 10
result = while_loop(a);
cout << "The result of while_loop is : " << result << endl;
return 0;
}