dimanche 20 février 2022

What causes this code to trigger implicit int narrowing?

The following code makes clang to fail when -Wc++11-narrowing is specified

#include <stdint.h>

extern uint8_t numbers[];
extern int n;

uint8_t test(int num) {
    uint8_t a{n > 0 ? *numbers : 2};
    return a;
}

(Same code in godbolt: https://godbolt.org/z/nTKqT7WGd)

8:15: error: non-constant-expression cannot be narrowed from type 'int' to 'uint8_t' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]
    uint8_t a{n > 0 ? *numbers : 2};

I read the standard and related issues but I cannot comprehend why a ternary operation with two results that are uint8_t or can be transparently narroweduint8_t (i.e: constant 2) result in a promotion to int that then wants to be explicitly narrowed.

Can someone explain why this happens? Thanks!

Aucun commentaire:

Enregistrer un commentaire