-2

I did the type conversion of variable b(declaration outside the scope) in a scope and give a new val to b, and when the scope ends, the val of b seem to be wrong.

This happens on my macbook, which version of gcc is gcc-8 (Homebrew GCC 8.3.0) 8.3.0. I tried the same code on my linux laptop whose gcc version is 5.4.0 and the code runs well.

std::vector<int> a = {1,2,3,4};
int b;
{
    size_t i = 0, b = a[i];
    //this time type of b is size_t

    ++i;
    b = a[i];
}
std::cout << "b = " << b << std::endl;

On my mac, the result is b = 0 On Ubuntu 16, the result is b = 1

What is the difference between two version of gcc on type conversion?

Or it is a bug?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 3
    `int b;` is never initialized - the result of `cout << "b = " << b << endl;` is *undefined behavior* – UnholySheep Apr 27 '19 at 09:42
  • 1
    Did you use `-Wall` when compiling? Did it tell you anything interesting about your code? You can also try `-Wshadow`. – Marc Glisse Apr 27 '19 at 10:10
  • On top of the given answer `size_t i = 0, b = a[i];` looks fishy to me. I'm not sure if the standard dictates a initialization order here. `b = a[i]` might be executed first before `i` is initialized. Any language lawyers? – Unimportant Apr 27 '19 at 10:46

1 Answers1

6

You're not doing any type conversion, you're creating a second b within the scope, that, due to it having the same name, shadows the outer b. This means that you're assigning something to the inner b and leaving the outer b untouched. Once the scope ends (at the closing curly brace), you're left with the (uninitialized) outer b, and printing it invokes undefined behavior, which is exactly what you're experiencing.

This piece of code is semantically equivalent and might show a bit better what is actually happening:

vector<int> a = {1,2,3,4};
int outer_b;
{
    size_t i = 0, inner_b = a[i];
    //this time type of b is size_t

    ++i;
    inner_b = a[i];

}
cout << "b = " << outer_b << endl;
rainer
  • 6,769
  • 3
  • 23
  • 37