Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11 auto compile time or runtime?

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?

like image 977
Pranit Kothari Avatar asked Oct 27 '13 13:10

Pranit Kothari


People also ask

Is auto resolved at compile time?

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

Is compile time or run 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 Auto slow in C++?

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.

Which is faster compile time or runtime?

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.


3 Answers

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.

like image 133
Siyuan Ren Avatar answered Sep 17 '22 19:09

Siyuan Ren


I just wanted to add some things that the other answers didn't address.

  1. every declaration must have a known type at compile time so auto doesn't get special treatment, it has to deduce the type at compile time.
  2. You are sort of mis interpreting how 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.
  3. People also seem to use auto quite a bit for iterators because their types are quite a pain to write but I'm not so sure this is an intended primary use of auto
like image 45
aaronman Avatar answered Sep 17 '22 19:09

aaronman


It's done completely at compile time, with no performance difference.

auto i = 2;

compiles the same as

int i = 2;
like image 26
vines Avatar answered Sep 16 '22 19:09

vines