I am getting confused between two concepts that is "auto" keyword that is introduced in C++11 and type casting (dynamic_cast/static_cast).
Does "auto" keyword in C++11 uses type casting internally?
I am getting confused between two concepts that is "auto" keyword that is introduced in C++11 and type casting (dynamic_cast/static_cast).
Does "auto" keyword in C++11 uses type casting internally?
Let's keep it simple using an example
unsigned short s = 65535;
auto positive = s;
auto negative = (short) s;
std::cout << positive << std::endl; // prints 65535
std::cout << negative << std::endl; // prints -1
In this code:
unsigned short
variable with value 655355
positive
and you let the compiler deduce its type from its initializer (see link). Therefore positive
will be unsigned short
because its initializer has that type.negative
's type will be deduced as short
, because you are casting the type of s
from unsigned short
to short
.Note that both positive
and negative
variables will hold the same value, which in hexadecimal is 0xffff
, but they are interpreted in different ways due to their types.
So there's not such a thing as a difference between auto and casting as if they were comparable, they are different concepts.
auto
will deduce the type or your variable based on certain rulesI recommend you to read Effective Modern C++ by Scott Meyers to learn about how auto
works.