0

I'm new to c++ and I want a variable that represents fuel to stay zero even if/when the program tries to subtract from it. The problem is that sometimes it becomes a rather large number. I am guess that the variable is looping to the highest number that it can be. But I could be misunderstanding the situation. If not how do I stop this. If I am miss understanding tell me what is going on.

This is an example

unsigned int num = 0;

	num = num - 1;
	cout << num;
5
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Duoas
0

You are right, the variable will wrap around to its highest value. The only way that I know of to avoid it is to do the following:

unsigned int num = 0;

num = (num < 1 ? 0 : num - 1);
cout << num;
0

Thanks mike.
What is that you did? I understand it but I'd like to look it up.

0

Actually, the best solution is to make the variable an int rather than unsigned. That is assuming your 'fuel' will never go beyond 2+ billion

0

yes, if you never expect to hold any negative values you better change the data type to int from unsigned int. This will solve the problem. This way it will only take values from 0 - 65565 (approximately)

0

...also, you need to check to see if the number would be less than zero after subtracting, not before: num = (num >= subtrahend) ? (num - subtrahend) : 0; If your number is signed, you can just use the proper <algorithm> num = max( 0, num - subtrahend ); Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.