Elementary Programming in C++: Evaluating Expressions and Operator Precedence

C++ expressions are evaluated in the same way as arithmetic expressions.

Writing numeric expressions in C++ involves a straightforward translation of an arithmetic expression using C++ operators. For example, the arithmetic expression can be translated into a C++ expression as

(3 + 4 * x) / 5 – 10 * (y – 5) * (a + b + c) / x +

 9 * (4 / x + (9 + x) / y)

Though C++ has its own way to evaluate an expression behind the scene, the result of a C++ expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rule for evaluating a C++ expression. Operators contained within pairs of parentheses are evaluated first. Parentheses can be nested, in which case the expression in the inner parentheses is evaluated first. When more than one operator is used in an expression, the following operator precedence rule is used to determine the order of evaluation.

  • Multiplication, division, and remainder operators are applied next. If an expression contains several multiplication, division, and remainder operators, they are applied from left to right.
  • Addition and subtraction operators are applied last. If an expression contains several addition and subtraction operators, they are applied from left to right.

Here is an example of how an expression is evaluated:

Listing 2.8 gives a program that converts a Fahrenheit degree to Celsius using the  formula .

Listing 2.8 FahrenheitToCelsius.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    // Enter a degree in Fahrenheit

7    double fahrenheit;

8    cout << “Enter a degree in Fahrenheit: “;

9    cin >> fahrenheit;

10

11    // Obtain a celsius degree

12    double celsius = (5.0 / 9) * (fahrenheit – 32);

13

14    // Display result

15    cout << “Fahrenheit ” << fahrenheit << ” is ” <<

16    celsius << ” in Celsius” << endl;

17

18    return 0;

19 }

Be careful when applying division. Division of two integers yields an integer in C++. 5/9 is translated to 5.0 / 9 instead of 5 / 9 in line 12, because 5 / 9 yields 0 in C++.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *