psudo
psudo

Reputation: 1558

Operator precedence in C explanation

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.

Upvotes: 1

Views: 342

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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;

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114310

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.

Upvotes: 2

timrau
timrau

Reputation: 23058

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

Upvotes: 1

Related Questions