1

I have the following code:

#include<stdio.h> void main(){ int x; x=1%9*4/5+8*3/9%2-9; printf("%d \n", x); } 

The output of the program is -9. When I tried to breakdown the code according to operator precedence(* / %,Multiplication/division/modulus,left-to-right) answer turns out to be -8.

Below is the breakdown of the code:

x=1%9*4/5+8*3/9%2-9; x=1%36/5+24/9%2-9; x=1%7+2%2-9; x=1+0-9; x=-8; 

Can someone explain how the output is -9.

4
  • 3
    I get 1%9*4/5+8*3/9%2-9 to be (1%9*4/5)+(8*3/9%2)-9. Multiplication, division and modulo operators all have same operator precedence and left-to-right associativity. Commented Jul 30, 2017 at 12:51
  • void main is wrong. main should return int. Commented Jul 30, 2017 at 12:55
  • Maybe you misinterpreted a precedence table that listed multiplication,division and modulus as three operators having the same precedence. Commented Jul 30, 2017 at 12:57
  • 1
    1 % 9 * 4 / 5 is evaluated left-to-right; same precedence, so it is ((1 % 9) * 4) / 5. Commented Jul 30, 2017 at 12:59

3 Answers 3

2

It appears that you consider modulo to have lower precedence than multiplication and division, when in fact it does not. Instead of

x = (1 % ((9 * 4) / 5)) + (((8 * 3) / 9) % 2) - 9; 

the expression you have really represents

x = (((1 % 9) * 4) / 5) + (((8 * 3) / 9) % 2) - 9; 

The modulo in the first summand is applied before the multiplication and division.

Sign up to request clarification or add additional context in comments.

Comments

1
x = 1%9*4/5+8*3/9%2-9 == 1*4/5+24/9%2-9 == 4/5+2%2-9 == 0+0-9 == -9 

1 Comment

Adding an explanation how it is computed will help
1

All these operators *, /, % belong to the category of multiplicative operators. Their grouping is more clearly described in the C++ Standard (the same is valid for the C Standard) 5.6 Multiplicative operators:

1 The multiplicative operators *, /, and % group left-to-right.

Thus this expression statement

x=1%9*4/5+8*3/9%2-9; 

is equivalent to the following statement

x = (( ( 1 % 9 ) * 4 ) / 5 ) + ( ( ( 8 * 3 ) / 9 ) % 2 ) - 9; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.