jeudi 5 mars 2020

Why static casting an unsingned char with value more than 127 inside a Ranged Based Loop will return a negative value? [closed]

Why static casting an unsingned char with value more than 127 inside a Ranged Based Loop will return a negative value (and keep decreasing)?

The results of this code is :

c is : 126

c is : 127

c is : -128

c is : -127

c is : -126

#include <iostream>
#include <vector>


int main()
{
    double c = 0;
    std::vector <unsigned char>  bits(5);

    bits[0] = 126;
    bits[1] = 127;
    bits[2] = 128;
    bits[3] = 129;
    bits[4] = 130;

    for (const char& b : bits)
    {
    c = static_cast<double>(b);
    std::cout<<"\n c is : "<<c;
    }



    return(0);
}

However if it is static casted outside the range based loop, it would show the correct value.

std::cout <<static_cast<double>(bits[3]);

Will show 129.

Can anyone expalain to me what happened inside the range based loop?

Thank you.

Aucun commentaire:

Enregistrer un commentaire