Search code examples
coperator-precedence

strange result with operators precedence in C


I just have simple question, I am aware of C language, A while ago i came across this piece of code:

int a;
a=12/8*8;

I tried it using codeblocks and result was that a=8 !!!!!
How did the compiler deal with that?

Thanks.


Solution

  • Due to operator precedence ( * and / have same precedence) and associativity (they have left to right associativity)

    12/8*8 is equal to (12/8)*8
    

    Due to integer division

    (12/8)*8 is equal to (1)*8
    

    Hence, the final value is 8.