Home >Backend Development >C++ >How Does Operator Precedence Differ from the Order of Evaluation in Programming?

How Does Operator Precedence Differ from the Order of Evaluation in Programming?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 04:31:12961browse

How Does Operator Precedence Differ from the Order of Evaluation in Programming?

What is the relation between operator precedence and order of evaluation?

Contrary to popular understanding, operator precedence does not fully determine the order of evaluation in programming. While precedence governs the order of value computations, the evaluation of operands themselves remains independent of precedence.

Example:

Consider the expression x < y < z. Precedence rules dictate that it should be parsed as (x < y) < z. However, a stack machine, for instance, might evaluate the expression as follows:

push(z);
push(y);
push(x);
test_less();  // compares TOS to TOS(1), pushes result on stack
test_less();  // compares TOS to TOS(1), pushes result on stack

This evaluates z before x or y, but still evaluates (x < y) and compares the result to z, as intended.

Evaluation and Side Effects:

Side effects, such as incrementing or decrementing a variable, are executed by a separate thread conceptually. This thread joins at the next sequence point. Consider the expression a = b c;. It could be executed as follows:

push(a);
push(b);
push(c+1);
side_effects_thread.queue(inc, b);
side_effects_thread.queue(inc, c);
add();
assign();
join(side_effects_thread);

Here, a is evaluated before b or c, even though it is the target of the assignment. Attempting to use a variable in any other part of an expression before the next sequence point results in undefined behavior.

The above is the detailed content of How Does Operator Precedence Differ from the Order of Evaluation in Programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn