12

For the following program:

#include <vector>
#include <iostream>

int main()
{
  std::vector<int> v = {"a", "b"};
  
  for(int i : v)
    std::cout << i << " ";   
}

clang prints 97 0. The ascii value of 'a' is 97, but I don't fully understand the output.

On the other hand, gcc throws an exception:

terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()

so I assume it's using the 2 argument constructor that takes the size and default value, where the size is computed from the address of the string literal "a".

If the program is well-formed, what is the correct behavior? Here's the code.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 1
    I think `"a"` and `"b"` implicitly convert to `const char *` and it thinks it's a range of `char` which would be convertible to `int`. – François Andrieux Jul 10 '20 at 13:49
  • Oh, that makes sense. So just UB because the pointers are not pointing to the same range? – cigien Jul 10 '20 at 13:51
  • I think so. I think I've seen this before, I'm checking for a duplicate. – François Andrieux Jul 10 '20 at 13:51
  • Perfect, thanks, I couldn't find one. – cigien Jul 10 '20 at 13:51
  • 1
    I was thinking of [this question](https://stackoverflow.com/questions/41507602/why-does-the-number-of-elements-in-a-initializer-list-cause-an-ambiguous-call-er) which is related but not a duplicate. – François Andrieux Jul 10 '20 at 13:52
  • 1
    Similar issue:[2d char vector printing spaces when printing the second column](https://stackoverflow.com/questions/62831470/2d-char-vector-printing-spaces-when-printing-second-column) – JeJo Jul 10 '20 at 15:50
  • @JeJo It's basically the same underlying issue. I came up with this question while trying to figure out that one :) – cigien Jul 10 '20 at 15:52

1 Answers1

14

I assume it's using the 2 argument constructor that takes the size and default value

No, it's using the constructor taking two input iterators. "a" and "b" could decay to pointer which is valid iterator. As the pointer (iterator) to const char, the dereferenced const char would be converted to int and added as the vector's element. Anyway the code has UB because "a" and "b" don't refer to valid range, "b" is not reachable from "a".

songyuanyao
  • 169,198
  • 16
  • 310
  • 405