Practical C Programming, 3rd Edition

I l @ ve RuBoard

C++ allows the use of assignment statements almost anyplace. For example, you can put an assignment statement inside another assignment statement:

// don't program like this average = total_value / (number_of_entries = last - first);

This is the equivalent of saying:

// program like this number_of_entries = last - first; average = total_value / number_of_entries;

The first version buries the assignment of number_of_entries inside the expression. Programs should be clear and simple and should not hide anything. The most important rule of programming is KEEP IT SIMPLE.

C++ also allows you to put assignment statements in the while conditional. For example:

// do not program like this while ((current_number = last_number + old_number) < 100) std::cout << "Term " << current_number << '\n';

Avoid this type of programming. Notice how much clearer the logic is in the following version:

// program like this while (true) { current_number = last_number + old_number; if (current_number >= 100) break; std::cout << "Term " << current_number << '\n'; }

Question 6-1: For some strange reason, the program in Example 6-4 thinks that everyone owes a balance of 0 dollars. Why?

Example 6-4. balance/balance.cpp

#include <iostream> int balance_owed; // amount owed int main( ) { std::cout << "Enter number of dollars owed:"; std::cin >> balance_owed; if (balance_owed = 0) std::cout << "You owe nothing.\n"; else std::cout << "You owe " << balance_owed << " dollars.\n"; return (0); }

Sample output:

Enter number of dollars owed: 12 You owe 0 dollars.

I l @ ve RuBoard

Категории