Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are innermost parentheses evaluated first in C?

Tags:

c

Consider the below question in regard to this expression: (a+b)+ (c +(d+e)) +(f+g)

In C we use precedence and associativity to decide which operator should be evaluated first and if there is more than one operator with the same precedence, then in what order they should be associated.

My question is:

  1. Is (d+e) evaluated first by the compiler as it is the innermost nested parenthesis in the expression?

  2. If so, do associativity and precedence somehow recommend innermost parenthesis evaluation should be done first?

  3. I strongly feel that it doesn't, and if it doesn't then why would the compiler even decide to evaluate the innermost parenthesis first? Because going from left to right and evaluating parentheses at the same level seems much more logical to me.

like image 758
codeitram Avatar asked Dec 08 '22 09:12

codeitram


2 Answers

You are confusing operator precedence with order of evaluation. These are different though related terms. See What is the difference between operator precedence and order of evaluation?

Specifically:

  1. Do (d+e) is evaluated first by compiler as it is innermost nested parenthesis in the expression?

This depends on the order of evaluation of the + (additive) operators, nothing else. The order is unspecified for + (as it is for most operators) and we can't know it, nor should we rely on it. Compilers are allowed to do as they please and don't need to tell you (document) how and when they pick a certain order.

  1. If so does associativity and precedence somehow explains innermost parenthesis evaluation should be done first?

No, this has nothing to do with operator precedence.

  1. I strongly feel that it doesn't and if it don't then why we decided to evaluate innermost parenthesis first, because going from left to right and evaluating parenthesis at same level seems much logical to me

See 1)

like image 198
Lundin Avatar answered Dec 29 '22 05:12

Lundin


Consider instead

(a() + b()) + (c() + (d() + e())) + (f() + g())

where each of the functions prints it's letter and, of course, returns a value

int a(void) { putchar('a'); return 42; }

When that expression is evaluated, something like "abcdefg" will be printed according to "order of evaluation", regardless of the operator precedence.

The order of evaluation is not something the Standard has rules for. Each compiler implementation can do the evaluation as it likes best ... even changing the order between compilations or runs.

like image 27
pmg Avatar answered Dec 29 '22 04:12

pmg