I have encountered the following VS2015 CTP6 VC++ compiler behavior:
unsigned char a = 1;
unsigned char x = (2 | a); //this compiles fine
unsigned char y[] = {2 | a}; //this emits warning C4838: conversion from
//'int' to 'unsigned char' requires a narrowing conversion
I assume that some implicit type conversion or promotion occurs in the definition of y
, but whatever is happening there should've happened in the line that defines x
as well - yet this line compiles fine.
Reversing the operands order didn't help, casting 2
to unsigned char
didn't help either:
unsigned char y[] = {(unsigned char)2 | a}; //same warning
unsigned char y[] = {a | 2}; //same warning
Same thing happens with other bitwise operators as well. The only thing that resolved the warning was an explicit cast of the result of bitwise operation: unsigned char y[] = {(unsigned char)(2 | a)};
Can anyone explain such compiler behavior? Is it a bug?
Edit:
GCC 4.9.1
compiles cleanly, Clang 3.5
issues an error: "error: non-constant-expression cannot be narrowed from type 'int' to 'unsigned char' in initializer list [-Wc++11-narrowing]". Can anyone explain?