Reputation: 4876
If I compile the following program:
#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]);
}
}
with g++ test.cpp -o test -std=c++11 -Wconversion
on gcc 4.9
it spits out the folowing warning:
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;
^
So if I understand it correctly this means that the compiler converts the single value of uint_8
to int
? Is this because of memory alignment?
On the other hand if I try something like:
uint8_t int8Value = 342;
it throws me an overflow
warning and trancates the result. Also
printf("%i\n",sizeof(int8Value));
returns the expected 1
.
Am I missing something obvious?
Upvotes: 1
Views: 4932
Reputation: 409482
Yes, arithmetic expression causes conversion to int
. See e.g. this reference.
Upvotes: 6