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;

Recommended Answers

All 5 Replies

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;

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

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

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)

...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.

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.