October 15, 2012

Simplify the if statement

years is an int.

if (years >= 1 || years <= -1) {
if (years != 0) {

Unnecessary loop

Break non-negative distance into two smaller numbers, years and days. Bug: days = 1; should be days = 0;. The last continue does nothing.

	int days = 0;
	int years = 0;

	for (int i = 0; i > distance; --i) {
		if (days < 365) {
			++days;
			continue;
		}
		days = 1;

		if (years < INT_MAX) {
			++years;
			continue;
		}
	}

See the remainder.C we did on Monday, September 24.

	int years = distance / 365;
	int days = distance % 365;

Switch statement should be if

distance is non-negative.

	int days;

	switch (distance < 365) {
	case 1:
		days = distance;
		break;

	case 0:
		days = distance % 365;
	}
	int days;	//uninitialized variable

	if (distance < 365) {
		days = distance;
	} else {
		days = distance % 365;
	}
	const int days = distance % 365;

No reason to keep the variable alive after the loop is over.

	int n, number = 0;
	int sum = 0;

	cout << "Enter number of integers, n, to sum: ";
	cin >> n;

	if (!cin) {
		cerr << "input failed\n";
		return EXIT_FAILURE;
	}

	while (number <= n) {
		sum += number;
		++number;
	}

	cout << "Sum: " << sum << "\n";

No reason to keep number alive after the loop is over. And there’s no reason to add zero to sum.

	cout << "Enter number of integers, n, to sum: ";
	int n;
	cin >> n;

	int sum = 0;
	for (int number = 1; number <= n; ++number) {
		sum += number;
	}

	cout << "Sum: " << sum << "\n";

Check for overflow and underflow

Part 1. Assume that quotient is non-negative. Why doesn’t this catch overflow?

	if (year + quotient > INT_MAX) {

To catch overflow, we can subtract quotient from both sides:

	if (year > INT_MAX - quotient) {

Part 2. Assume that quotient is negative. Why doesn’t this catch underflow?

	if (year + quotient < INT_MIN) {

To catch underflow, we can subtract quotient from both sides:

	if (year < INT_MIN - quotient) {

Part 3. Catch overflow and underflow.

	if (quotent >= 0) {
		if (year > INT_MAX - quotient) {
			cerr << "overflow\n";
		}
	} else {
		if (year < INT_MIN - quotient) {
			cerr << "underflow\n";
		}
	}

The following code does the same thing, but the above code is more symmetrical.

	if (quotent >= 0) {
		if (year > INT_MAX - quotient) {
			cerr << "overflow\n";
		}
	} else if (year < INT_MIN - quotient) {
		cerr << "underflow\n";
	}