while, return 0; ?

What does the while loop actually do and what does that (true) at the start mean. I would also like to know why are there 2 "return 0;" instead of one at the end.

and why is the reservation for "started" -1? what does - do

I appreciate any kind of help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
float ncs; //the number that is given to us by the user
	long cd; //whole part of the number
	float ncds; //decimal part of the number
	int started = -1; //please explain to me why is there a -



 while (true) {
		if (started != -1) {
			cout << "Do you want to restart the program? (1 - YES, 0 - NO)" << endl; 
			while (started < 0 || started > 1)
				cin >> started; //
			if (started == 0)
				return 0;
		}

		for (int i = 0; i < 2; i++) 
		{
			cout << "Enter a decimal number" << endl; 
			cin >> ncs; 
			cd = (long)ncs;
			ncds = ncs - cd; 
			cout << "For " << i + 1 << ". number, which is " << ncs       
				<< " applies that ";  
			cout << "decimal part equals " << ncds << ", whole part equals ";
			cout << cd << endl; 

		}
		started = -2;

	}

	return 0;
	system("pause");
}
Last edited on
That's a minus sign, it indicates that the number has a negative value. The while loop keeps the program running until the user wishes to exit. Functions often have multiple return points to indicate their state when they exit, or, as in this case, because the author did not put enough thought into program flow.
1
2
3
4
while (condition)
{
	// Code to run as long as condition is true
}

What you see inside the parenthesis is the loop condition. If the condition is true the code inside the loop will run. If the condition is true at the end of the loop the code will run again, and again, and again ... until the loop condition becomes false.

In your code the loop condition is always true so it will never make the loop stop but there are other ways that the loop can be stopped. In your code return is used to stop the loop.

All functions (except void functions) returns a value. To return a value from a function we use the return statement. Return will also end the function right away. In you code you don't seem to be very interested in the return value but instead you use return on line 14 to end the function. If this is the main function then it will end the whole program.

Note that the code you have after the loop will never run because return ends the whole function. If you just want to end the loop you can use break instead.
Last edited on
What is the correct way to write this with 1 "return 0;" ?
You could simply remove the return from line 33 because it will never be reached.

Another way is to replace the return on line 14 with break;. So instead of returning directly the break will end the loop and return on line 33 instead.
Ok, thank your for your help!
Topic archived. No new replies allowed.