Consider the following
auto a = 10;
When does the compiler know that a
is an int
, at compile time or at run-time? If it deduces the type at run-time, will it not affect the performance?
Even when a variable is declared auto, its type is fixed at compile time.
Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.
Is it faster: The simple answer is Yes, by using it a lot of type conversions could be omitted, however, if not used properly it could become great source of errors.
Compilers will compile these codes first before execution. That is, they will first convert the program codes into machine codes, and then commit them to memory before they start execution of said code. Compilers are faster after the first execution of the same code that has not changed since compilation.
Compile time. In C++, runtime type information is stripped during compilation(without RTTI or virtual inheritance). It is not possible, in fact, to inspect the primitive type at runtime.
I just wanted to add some things that the other answers didn't address.
auto
doesn't get special treatment, it has to deduce the type at compile time. auto
should be used. Yes you can do auto i = 2;
and it works fine. But a situation where you need auto is a lambda for example. A lambda does not have a namable type (although you can assign it to an std::function
). Another situation it is useful for is inside a class or function template it can be extremely difficult to figure out the type of certain operations (maybe sometimes impossible), for example when a function is called on a template type that function may return something different depending on the type given, with multiple types this can become essentially impossible to figure out which type it will return. You could of course just wrap the function in a decltype
to figure out the return but an auto
is much cleaner to write. auto
It's done completely at compile time, with no performance difference.
auto i = 2;
compiles the same as
int i = 2;
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