C++Language FeatureLearn C++

Learn How To Use Auto-Typed Variables In C++ For Windows Development

Image

auto-typed variables is a C++11 feature that allows the programmer to declare a variable of type auto, the type itself being deduced from the variable’s initializer expression. The auto keyword is treated as a simple type specifier (that can be used with * and &), and its semantics are deduced from the initializer expression.

auto-typed Variables Examples

int IntFnc() {}
bool BoolFunc() {}
char* CharSFunc() {}
    
int _tmain(int argc, _TCHAR* argv[]) 
{
    // x is int
    auto x = IntFunc();
    // y is const bool
    const auto y = BoolFunc();
    // w is char*
    auto w = CharSFunc();

    return 0;
}

Multi-declarator auto

The C++11 standard includes the multi-variable form of auto declarations, such as:

int* func(){}

int _tmain(int argc, _TCHAR* argv[])
{
        auto x = 3, * y = func(), z = 4;
        return 0;
}

The restriction with multi-declarator auto expressions is that the variables must have the same base type. For example, the following line of code is well-formed:

auto x = 3, y = *(new int);

because x and y have the same base type : int, while the following code:

auto x = 3, y = 3.5;

will generate the error: [bcc64 Error] File1.cpp(11): 'auto' deduced as 'int' in declaration of 'x' and deduced as 'double' in declaration of 'y'. This feature is supported by the Clang-enhanced C++ compilers.

Check out all of the modern C++ language features supported in the latest C++Builder for Windows development.

Image

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++C++11C++14C++17C++20Introduction to C++Learn C++

Learn Copy Constructors in C++ Classes

C++C++11C++14C++17Introduction to C++Learn C++Syntax

Learn How To Use Types Of Destructors In C++?

C++C++11C++14Learn C++Syntax

How To Convert u32string To A wstring In C++

C++C++11C++14C++17C++20Introduction to C++Learn C++

How To Learn The Move Constructors In Modern C++?