1) I have read many times about undefined behavior in C. That is about : some behavior that C doesn’t say in its definition, so each compiler will have their implementation but not violate C standard. Example are : x= ++y*4 + ++y*3.
But, anyone here can give me two compiler that give different result ? I feel interested to test with it. (in my machine, I just have mingw)
2) And, C doesn’t say about order of + - * / operation. For example : 1*2 + 3 + 4*5. * / will be calculate first, but we don’t know its other.
So according to below example : if we have :
int a, b, c;
// assign value for a,b,c
float result = a*b/c; // wrong
float result = (float)a*b/c; // seem true
But, b/c still can be calculate first, so the answer will be wrong. so, the true type-cast should be:
float result = a*b/(float)c
But, nearly, all books about C, all people coding C, always use : (float)a*b/c . Is it ALWAYS true, or they trust “normal compiler` will solve from left to right like we often think ?
Please give me clearer about this point.
Thanks 🙂
For 1) your are mixing up undefined behavior and unspecified behavior, they are not the same.
This ugly expression that you give has undefined behavior; what you think are the consequences of undefined behavior is just unspecific behavior, namely that compilers chose one of different possibilities, which often is something that you can live with.
Undefined behavior can be much worse. If the behavior is undefined the compiler can generally chose anything to its liking, eat your lunch, empty your bank account, crash your computer. And unfortunately there are situations where compilers will do bad things that you don’t expect in these cases. So just don’t provoke UB in the first place.