# V3151. Potential division by zero. Variable was used as a divisor before it was compared to zero. Check lines: N1, N2.

The analyzer has detected a potential division-by-zero error.

What the analyzer is reporting is a situation where some value is divided by a variable and then this variable is compared with zero. This means one of the two scenarios:

1) If the divisor variable has the value 0, an error will occur.

2) The division always yields a correct result because the divisor variable is never 0. In this case, the null check is unnecessary.

Consider the following example:

    int Foo(int num)
    {
      result = 1 / num;
      if (num == 0) return -1;
      ....
    }

If the value of 'num' happens to be zero, executing the '1 / num' expression will lead to an error. The analyzer reports this code by pointing at two lines: the first is where the division is executed and the second is where the divisor variable is checked for null.

Fixed code:

    int Foo(int num)
    {
      if (num == 0) return -1;
      result = 1 / num;
      ....
    }

The following example demonstrates the scenario where no error occurs and the null check is not needed.

    int num = MyOneTenRandom();
    result = 1 % num;
    if (num == 0) return -1;

This code is always correct. The 'MyOneTenRandom' function is implemented in such a way that it never returns zero. However, the analyzer failed to recognize this (which may happen when, for example, the method is virtual and the interprocedural analysis fails to determine which of its implementations will be called at runtime) and issued the warning. To eliminate it, remove the check "if (num == 0)" – it has no practical use and can only confuse the maintainer.

Fixed code:

    int num = MyOneTenRandom();
    result = 1 % num;

As an alternative to removing the check to eliminate a false positive, you can also use a warning-suppression comment, for example: "1 % num; //-V3151".

This diagnostic is classified as:

CWE-369