Prior to the 1999 version of C, the result of division was considered compiler-dependent. This left the option to the compiler vendor to decide whether its customers would prefer fast division or consistent division. Division by a compile-time-known value of 2 could be done with an arithmetic right shift of one bit. On a 2s-complement machine, this would correspond to floor behavior; on a 1s complement machine it would correspond to truncation toward 0. Such a bit shift was much faster than actual division. If the divisor was not known to be 2 at compile time, the compiler would generate code to perform an actual division; if the divisor happened to be 2 for a particular division, the result would be truncated to 0. Thus, on a 2s-complement machine, one compiler would be allowed for dividing −7 by 2 to return −4 in some cases and −3 in other cases within one program.
Starting with 1999, C required compilers to perform integer division as truncation toward 0 in order to achieve more predictable behavior.
Another issue is that if one writes code with −7/2, it is treated as −(7/2) which would nearly always be evaluated as −3 regardless of compiler and hardware behavior. That is because in C, − is always a unary operator; there is no such thing as negative integer literals in C. People often forget this detail and are surprised.
Comment
Prior to the 1999 version of C, the result of division was considered compiler-dependent. This left the option to the compiler vendor to decide whether its customers would prefer fast division or consistent division. Division by a compile-time-known value of 2 could be done with an arithmetic right shift of one bit. On a 2s-complement machine, this would correspond to floor behavior; on a 1s complement machine it would correspond to truncation toward 0. Such a bit shift was much faster than actual division. If the divisor was not known to be 2 at compile time, the compiler would generate code to perform an actual division; if the divisor happened to be 2 for a particular division, the result would be truncated to 0. Thus, on a 2s-complement machine, one compiler would be allowed for dividing −7 by 2 to return −4 in some cases and −3 in other cases within one program.
Starting with 1999, C required compilers to perform integer division as truncation toward 0 in order to achieve more predictable behavior.
Another issue is that if one writes code with −7/2, it is treated as −(7/2) which would nearly always be evaluated as −3 regardless of compiler and hardware behavior. That is because in C, − is always a unary operator; there is no such thing as negative integer literals in C. People often forget this detail and are surprised.
Parent comment
in c language the division of -3/2 is -2 but compiler is giving -1 why?