Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code compile (C++11) without a type mismatch error?

std::vector<char> p = {"abc", "def"}; 

"abc" and "def" are not char, why doesn't the compiler give me an error about this type mismatch?

like image 203
ebi Avatar asked Jan 28 '18 01:01

ebi


People also ask

What is a mismatch error?

This error indicates that Access cannot match an input value to the data type it expects for the value. For example, if you give Access a text string when it is expecting a number, you receive a data type mismatch error.

What is type mismatch in programming?

Sometimes, while writing code, programmers may ask that a value be stored in a variable that is not typed correctly, such as putting a number with fractions into a variable that is expecting only an integer. In such circumstances, the result is a type-mismatch error.

What is type mismatch error in C++?

E2356 Type mismatch in redeclaration of 'identifier' (C++)Your source file redeclared a variable with a different type than was originally declared for the variable. Possible Causes. This can occur if a function is called and subsequently declared to return something other than an integer.


1 Answers

You're not calling vector's constructor that takes an initializer_list<char>. That constructor is not viable because, as you said, you're not passing a list of chars.

But vector also has a constructor that takes iterators to a range of elements.

template< class InputIt > vector( InputIt first, InputIt last,         const Allocator& alloc = Allocator() ); 

Unfortunately, this constructor matches because the two arguments will each implicitly convert to char const *. But your code has undefined behavior because the begin and end iterators being passed to the constructor are not a valid range.

like image 186
Praetorian Avatar answered Oct 20 '22 18:10

Praetorian