gcc是否将uint8_t转换为int以获取单个值?

时间:2014-08-08 06:44:19

标签: c++ gcc c++11 implicit-conversion type-conversion

如果我编译以下程序:

#include <vector>
#include <cstdint>
#include <stdio.h>

int main() {
    constexpr std::size_t N = 10;
    uint8_t int8Value = 42;

    std::vector<int> IntVector(N, 0);
    for (int & ele:IntVector) {
        ele += int8Value;
    }

    std::vector<uint8_t> Int8Vector(N, 0);
    for (uint8_t & ele:Int8Vector) {
        ele += int8Value;
    }

    for (std::size_t i = 0; i < N; i++) {
        printf("%i %i\n",IntVector[i],Int8Vector[i]);
    }
}
<{1>} g++ test.cpp -o test -std=c++11 -Wconversion gcc 4.9它会发出以下警告:

test.cpp: In function ‘int main()’:
test.cpp:16:7: warning: conversion to ‘uint8_t {aka unsigned char}’ from ‘int’ may alter its value [-Wconversion]
ele += int8Value;
   ^

因此,如果我理解正确,这意味着编译器会将uint_8的单个值转换为int?这是因为内存对齐吗?

另一方面,如果我尝试这样的话:

uint8_t int8Value = 342;

它会向我发出overflow警告并转换结果。还

printf("%i\n",sizeof(int8Value));

返回预期的1

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:6)

是的,算术表达式会导致转换为int。参见例如this reference