auto

From RAD Studio
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


The auto keyword has been redefined in the C++11 and C++17 standards. Thus, C++Builder supports different definitions of auto, determined by the standard that each C++ compiler follows.

This page describes the definitions of auto.

C++98 Definition

Category

Storage Class Specifiers (C++)

Syntax

[auto] <data-definition> ;

Description

Use the auto modifier to define a local variable as having a local lifetime.

This is the default for local variables and is rarely used.

Example:

void f() {
        auto int x;
}

C++11 Definition

Category

Type Specifiers

Syntax

[auto] <variable_name> = <initializer_expression> ;

Description

Use auto as a simple type specifier that deduces its semantics from the initializer expression.

Example:

int f() {
        return 1;
}

int _tmain(int argc, _TCHAR* argv[]) {
        auto x = f();
        return 0;
}

In this example, the type of the variable x is deduced from its initializer expression: f(). Therefore, x would be of type int, the type returned by f().

C++14 definition

In C++14, auto can be used as a return type for a method, deducing the return type, as well as for type inference for a variable or constant, as in C++11.

Example:

// C++14 introduces using the auto keyword for a return type
auto MyMethod() {
    return Hello world;
}
int _tmain(int argc, _TCHAR* argv[]) {
// C++11 introduced type deduction for a variable / constant
        auto x = MyMethod();
        return 0;
}

C++17 Definition

In C++17, auto can be used in a template parameter to deduce the type, and for structured bindings.

Structured bindings allow you to easily tie individual variables to elements of a tuple. This means a method using std::tuple to effectively return multiple return values can have those values assigned to multiple individual variables in the calling method.

Example:

std::tuple<int, float> returnMultiple()

{ int i = 1; float f = 3.14; return std::make_tuple(i, f); }
// In the calling method, with i and f predefined variables:
auto [i, f] = returnMultiple();

Code Migration Issue

When Clang-enhanced C++ compilers encounter old auto syntax (that is, auto used as a storage class specifier), they raise the following warning:

[<compiler> Warning] File1.cpp(12): 'auto' storage class specifier is not permitted in C++11, and will not be supported in future releases.

See Also