Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++ - bitwise shift promotes unsigned char to int

The following code:

unsigned char result;
result = (result << 4 );

Compiled with gcc version 4.6.4 (Debian 4.6.4-2), with the -Wconversion flag results in the warning

warning: conversion to 'unsigned char' from 'int' may alter its value [-Wconversion]

Why is that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because the standard says so. The operands to binary operators undergo integral promotion, in which anything smaller than an int is promoted to int; the results of the operation have type int as well. And if the original value were, say, 0x12, the results would be 0x120, and assigning this to an unsigned char will cause a change in value. (The assigned value will be 0x20.) Whence the warning.

EDIT:

From the standard (§5.8 Shift operators): " The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand." Unlike other binary operators, there is no effort to find a common type from the two operators: the result type is that of the left operand, period. But integral promotion does still occur: the unsigned char will be promoted to int (or to unsigned int if int has a size of 1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...