First two links to explain my doubts:
Http://en.cppreference.com/w/cpp/language/operator_arithmetic
Https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx
At first I was looking at <<expert C programming-Deep C secrets>> This book (Chinese translation c expert programming), Chapter 1 inside how quite was a quite change this section , there is a code like this:
#include <stdio.h>
intMain ()
{
if(-1< (unsignedChar)1)
printf"-1 is less than (unsigned char) 1:ansi semantics.\n");
Else
printf"-1 is not less than (unsigned char) 1:k&r semantics.\n");
return0;
}
I used vs2013 and GCC 4.9.1 to compile and run separately, which is the semantics of ANSI. Prints the first statement.
and change it.
#include <stdio.h>
intMain ()
{
if(-1< (unsignedint)1)//or a unsigned .
printf"1111111111.\n");
Else
printf"222222222222222.\n");
return0;
}
The result of the GCC 4.9.1 compilation run (without any special compilation options) is to print the second article. The vs2013 default compilation does not pass, error: Negative numbers are converted to unsigned numbers.
Start looking at <<expert C programming--deep C secrets>> This book is a bit lazy here, only remember these two words:
Operands with different types get converted when you do arithmetic. Everything is converted to the type of the floatest, longest operand, signed if possible without losing bits.
The whole rule is actually the two links at the beginning of this article.
I think the best practice should be as few as possible to cast, who want to remember those boring rules.
Arithmetic conversion for C (casting rules for arithmetic operations)