Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can auto distinguish short from long at compile time?

Tags:

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?

like image 933
David Lobron Avatar asked Feb 26 '18 15:02

David Lobron


People also ask

Is Auto determined at compile time?

Even when a variable is declared auto, its type is fixed at compile time.

How do you write short in C++?

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.


1 Answers

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.

like image 94
Ron Avatar answered Oct 20 '22 01:10

Ron