Skip to main content

IAR Embedded Workbench for RISC-V 3.40

CERT-INT35-C

In this section:
Synopsis

Use correct integer precisions.

Enabled by default

Yes

Severity/Certainty

Low/Low

lowlow.png
Full description

Integer types in C have both a size and a precision. Padding bits contribute to the integer's size, but not to its precision. Consequently, inferring the precision of an integer type from its size may result in too large a value, which can then lead to incorrect assumptions about the numeric range of these types.

Coding standards
CERT INT35-C

Evaluate integer expressions in a larger size before comparing or assigning to that size

CWE 681

Incorrect Conversion between Numeric Types

Code examples

The following code example fails the check and will give a warning:

#include <limits.h>

unsigned int pow2(unsigned int exp) {
    if (exp >= sizeof(unsigned int) * CHAR_BIT) {
        /* Handle error */
    }
    return 1 << exp;
}

The following code example passes the check and will not give a warning about this issue:

#include <stddef.h>
#include <stdint.h>
#include <limits.h>

/* Returns the number of set bits */
size_t popcount(uintmax_t num) {
    size_t precision = 0;
    while (num != 0) {
        if (num % 2 == 1) {
            precision++;
        }
        num >>= 1;
    }
    return precision;
}
#define PRECISION(umax_value) popcount(umax_value)

unsigned int pow2(unsigned int exp) {
    if (exp >= PRECISION(UINT_MAX)) {
        /* Handle error */
    }
    return 1 << exp;
}