Will the result be realized if one or two of the operands of the operator / or% are negative numbers?

eg. What are the meanings of these expressions? Do they depend on the compiler?

-7/3   -7%3
7/-3   7%-3
-7/-3  -7%-3
+4
source share
3 answers

In C89, the division result /can be truncated in any case for negative operands.

In C99 or later, the result will be truncated to zero.

The operator %depends on behavior /in all standards.


Literature:

C89 § 3.3.5

, / , , , , %. a/b . (a/b) * b + a%b a.

C11 § 6.5.5

, / ,

:

" "

+6

% /( ,/ , % .), , , , . C , :

  • PEMDAS: Parenthesis, Exponent, Multiply/Divide, Add/Subtract.
  • Multiply/Divide . .
0

, . / %

(a / b) * b + (a % b) == a

The C89 / 90 standard says that the result of division is determined by implementation: the compiler is allowed to implement either Euclidean division (truncation towards negative infinity, non-negative remainder), or Fortran-style division (truncation to zero, possibly a negative remainder).

In Euclidean division

-7/3 = -3  -7%3 = 2
7/-3 = -2  7%-3 = 1
-7/-3 = 3 -7%-3 = 2

In the formatted style section

-7/3 = -2  -7%3 = -1
7/-3 = -2  7%-3 = 1
-7/-3 = 2 -7%-3 = -1

The C99 standard (and later) requires all C compilers to implement Fortran-style partitioning.

Side note: C ++ adheres to an implementation-specific specification, up to C ++ 03. C ++ 11 requires, in particular, Fortan's separation.

0
source

All Articles