简体   繁体   中英

Operators precedence in C Programming

I am currently learning C Programming ( my first programming language ). I am a little bit confused with the operators precedence. Arithmetic operators precedence are as follows.

  1. *
  2. /
  3. %
  4. +
  5. -

This is what is given in my book at least. What i am confused is about how do i go solving expressions when it comes to my theory exams ? I tried solving many expressing with the order given above but fail to get a correct answer.

Given the following definitions:

int a = 10, b = 20, c;

How would we solve this expression?

a + 4/6 * 6/2 

This is an example in my book.

The precedence of / and * is the same in C, just as it is in mathematics. The problem is that in mathematics the following expressions are equivalent, whereas in C they might not be:

(a/b) * (c/d)
(a/b*c) / d

These aren't equivalent in C because if a , b , c , and d are integers, the / operator means integer division (it yields only the integral part of the result).

For example,

(7/2)*(4/5); //yelds 0, because 4/5 == 0
(7/2*4)/5; //yields 2

A general good coding practice is being explicit about your intentions. In particular, parenthesize when in doubt. And sometimes even when you're not.

    a + 4/6 * 6/2 
 = 10 + 4/6 * 6/2
 = 10 + 0*6/2
 = 10 + 0/2
 = 10

Note that 4/6 evaluates to 0 as integer division is used.

一种安全的实际解决方案是始终使用括号()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM