Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is the order of evaluation in C?

Sheza Munir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Precedence and associativity

Order of evaluation refers to the operator precedence and associativity rules according to which mathematical expressions are evaluated.

Same precedence

Operators in the same row have the same precedence. The compiler will evaluate them in any order.

It may choose another order when the same expression is evaluated again, but this will not affect the evaluated answer.

Different precedence

Operators in different rows have different precedence. Rows are in order of decreasing precedence. This means that below a given row, any operator in the lower rows will have lower precedence than the operators in the highest row.

Altering the order

The order of precedence can be altered by using parentheses around the parts of the mathematical expression that needs to be evaluated first.

Table of the order of evaluation

The order of evaluation in C is illustrated in the following figure:

#include <stdio.h>

int main() {
  int answer_1 = 0; // stores order evaluated answer
  int answer_2 = 0; // stores left to right evaluation
  
  answer_1 = 2 * 3 + 4 / 2;
  answer_2 = 2 * (3 + 4) / 2;

  printf("Answer with order of evaluation: %d\n", answer_1);
  printf("Answer without order of evaluation: %d\n", answer_2);

  return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring