I was dabbling in OCaml when I realized that it buckets integer division and multiplication into the same precedence level, so 3*4/5
is different from 3/5*4
. Somehow I incorrectly remembered that this is not the case in C/C++, and that division has higher precedence than multiplication but every piece of documentation said that exactly like OCaml C and C++ assign the same precedence to both /
and *
.
I wrote a simple program:
int main(int argc, char** argv){
printf("%f %f",3*5/4, 3/5*4);
}
When I compiled this with gcc 8.1.1, it printed 0.0000 0.0000 which, although it reinforced my incorrect belief, went against the documented behavior. Suspecting some weird compiler issue, I tried to simply print an integer formatted as a float:
int main(int argc, char** argv){
printf("%f",20);
}
and once again got 0.00000 as the result. This is really messing with my brain. It's 2AM and I cannot sleep without getting an answer.
P.S.: I have programmed in C for many years and there's either something extremely silly that I am doing here or the compiler is really messing things up.
Edit: It was a silly error as pointed out in the comments. In C/C++ /
will act like proper division if, at least, one of the operands is a float but it becomes integer division when both operands are integers. Also printf()
cannot perform any conversion as it has no idea about the actual type of a variable. I earned at least one downvote but it will be a lasting reminder of where bad default semantics and lax typing can bite.