Getting error in use of auto for the implicit conversion.
Capturing the return of v.size() using int variable is ok but auto complains.
Compiler error does inform it is because of narrowing conversion .But I would like to understand in terms memory how this happens and why auto is not allowing it do that whereas normal conversion is ok
#include <iostream>
#include <vector>
int main()
{
auto v = std::vector<int>{ 1, 2, 3 };
auto c = 'h';
auto n2 = int{c};
std::cout<<n2<<" "<<c;
auto size = int{v.size()};
std::cout<<size;
int size_1 = v.size();
std::cout<<size_1;
}
Error because of below line auto size = int{v.size()};
main.cpp: In function 'int main()': main.cpp:11:27: error: narrowing conversion of 'v.std::vector::size()' from 'std::vector::size_type {aka long unsigned int}' to 'int' inside { } [-Wnarrowing]
When that line is commented it works perfectly
#include <iostream>
#include <vector>
int main()
{
auto v = std::vector<int>{ 1, 2, 3 };
auto c = 'h';
auto n2 = int{c};
std::cout<<n2<<" "<<c;
//auto size = int{v.size()};
//std::cout<<size;
int size_1 = v.size();
std::cout<<size_1;
}
Output
104 h3
long unsigned inttoint- which may truncate it. That's bad and you should be glad your friendly compiler warns you about it. - Jesper Juhlsize()does not returnint. There is conversion happening and the result may not be what you expect. Braced initialization (and the compiler warning) is saving you from making a mistake here. - Jesper Juhl