Understanding Negative Number Operations in C Language

First, let’s pose a question: what do you think the output of the following code will be?

/*  A simple example code */
#include <stdio.h>


int main(int argc, char const *argv[])
{
    int a = -10;
    int b = 10;
    int c = -3;
    int d = 3;

    printf("Result 1: %d\n", a%d);
    printf("Result 2: %d\n", b%c);
    printf("Result 3: %d\n", a%c);

    printf("Result 4: %d\n", a/d);
    printf("Result 5: %d\n", b/c);
    printf("Result 6: %d\n", a/c);

    return 0;
}
  • Yesterday, I helped a junior colleague at the company troubleshoot an issue. The colleague described that while implementing a simple feature to input a set of data for arithmetic operations, including addition, subtraction, multiplication, and division, the results of the division operation were sometimes correct and sometimes incorrect. They asked for my help to find out the cause.
  • First, I checked the variable types defined by them, which were of int type, and there was no issue there. However, the phenomenon was that the results were sometimes correct and sometimes incorrect. I found that the problem occurred when negative numbers were involved, which gave me a clue about the source of the issue.
  • Let’s take a look at the output of the example code above. Does it match your expectations?

Understanding Negative Number Operations in C Language

Rules for Remainder and Division with Negative Numbers in C Language

  • First, let’s consider why the signs differ during remainder and division in the example code above. This involves the issue of signs when negative numbers participate in division in C language.

When performing division with negative numbers in C language, the quotient is the number that is closest to the absolute value of the numerator, which does not exceed the absolute value of the denominator when multiplied.

  • For the remainder, the sign of the remainder is the same as that of the dividend (the numerator);
  • For the division, first, take the absolute values of all signed numbers and then perform division, determining the sign of the quotient based on the number of negative signs.

Conclusion

This issue may seem simple in C language, but it can lead to significant problems if not paid attention to. If this has been of any help to you, then it is worth it.
Understanding Negative Number Operations in C Language

END

Source: Linux Armory

Copyright belongs to the original author, please contact for deletion if there is any infringement.

Recommended Reading

How Fast Can GPIO Toggle?

What Products Can Be Made with Embedded Systems? I Realized After Dismantling My Home!

Can Programmers Who Don’t Understand Makefile Still Write Code?

→ Follow to Stay Updated ←

Leave a Comment