如果我编译以下程序:
#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
。
我错过了一些明显的东西吗?