I'm excited to use auto
variables in my C++ programs. I know variables declared with auto
use template rules to deduce variable types, but I'm confused as to how that works for numeric types. Suppose I have:
auto foo = 12;
The type for foo
could reasonably be int
or even unsigned char
. But suppose that later in my program I do some math and assign foo a value of 4 billion. At that point, I would want foo
to become type unsigned int
or perhaps long
.
How can compilers anticipate values that will be assigned later in the program?
Even when a variable is declared auto, its type is fixed at compile time.
short type Modifier We can use short for small integers (in the range −32,767 to 32,767). For example, // small integer short a = 12345; Here, a is a short integer variable.
The compiler works with the information present which in your case is the integer literal 12
. So it deduces the foo
to be of type int
. It does not anticipate anything. You can use the appropriate integer literal suffix:
auto foo = 12ul;
to force the foo
to be deduced as unsigned long
. You can't define the variable to be of type int
and then down the line expect the compiler to somehow change it into another type just because you assigned a different value that will not fit into previously used type. If you did that it would simply result in integer overflow which is undefined behavior.
For more info on the subject check out the auto specifier and auto type deduction reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With