From cb971eece803c13c8a0dda3841dc1ab830164253 Mon Sep 17 00:00:00 2001 From: Anass Al Date: Thu, 8 Oct 2020 08:00:40 -0700 Subject: [PATCH] [C++] Fix -Wnarrowing and -Woverflow due to signed bitfields on G++ ARM (#6163) Older versions of GCC (at least on ARM) complain about narrowing conversions and overflows when setting the reference index (defined as an 11-bit signed integer bitfield) to -1: ``` error: narrowing conversion of '-1' from 'int' to 'short unsigned int' inside { } [-Wnarrowing] error: conversion from 'short unsigned int' to 'short unsigned int:11' changes value from '65535' to '2047' ``` This is due to the signedness of integer bitfields (not explicitly signed or unsigned) being implementation-defined. This addresses this issue by explicitly defining the signedness of all the bitfields in `flatbuffers::TypeCode` in C++. --- include/flatbuffers/flatbuffers.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 279afd545..69c8d71b4 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -2745,10 +2745,13 @@ inline const char * const *ElementaryTypeNames() { // clang-format on // Basic type info cost just 16bits per field! +// We're explicitly defining the signedness since the signedness of integer +// bitfields is otherwise implementation-defined and causes warnings on older +// GCC compilers. struct TypeCode { - uint16_t base_type : 4; // ElementaryType - uint16_t is_repeating : 1; // Either vector (in table) or array (in struct) - int16_t sequence_ref : 11; // Index into type_refs below, or -1 for none. + unsigned short base_type : 4; // ElementaryType + unsigned short is_repeating : 1; // Either vector (in table) or array (in struct) + signed short sequence_ref : 11; // Index into type_refs below, or -1 for none. }; static_assert(sizeof(TypeCode) == 2, "TypeCode");