Reading assignment - auto variables

1 - What is an auto variable?

An auto variable is a placeholder type specifier whose type will be automatically deduced from the initializer.

2 - Why is it convenient to use?

Gives flexibility to functions when the type is unknown or when using multiple variable types.

3 - When should you use it?

When you don’t know what variable types will be passed in.

4 - When will the type of an auto variable be determined (compile-time or run-time)?

The type of an auto variable will be determined at compile time as the compiler automatically detects the variable’s data type.

1 Like
  1. What is an auto variable?

an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable’s scope. The scope is the lexical context, particularly the function or block in which a variable is defined.

  1. Why is it convenient to use?

Allows a programmer to leave the type deduction to the compiler itself.
With type inference capabilities, we can spend less time having to write out things the compiler already knows.

  1. When should you use it?

Good use of auto is to avoid long initializations when creating iterators for containers. The variable declared with auto keyword should be initialized at the time of its declaration only or else there will be a compile-time error.
The auto keyword has many uses, including but not limited to variables, functions, pointers, iterators, templates, and many more.

  1. When will the type of an auto variable be determined (compile-time or run-time?)

Compile-time. Types cannot be determined at runtime. The type of every expression must be known at compile time.