Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Auto | Other Data Types and Concepts
C++ Data Types
course content

Conteúdo do Curso

C++ Data Types

C++ Data Types

1. Introduction
2. Numerical Data Types
3. Text Data Type
4. Other Data Types and Concepts

bookAuto

Although C++ is a typed language, you can use auto when initializing a variable to determine the type automatically. This feature was introduced in C++14 and does not work with older versions.
Here is an example:

cpp

main

copy
12345678910
#include <iostream> int main() { auto num = 9; auto str = "I am string"; std::cout << num << std::endl; std::cout << str << std::endl; }

Note that it is harder to catch errors when using auto. Consider the example:

cpp

main

copy
1234567891011
#include <iostream> int main() { auto num1 = 9; auto num2 = 12; auto num3 = 15000; auto calculations = num1 / num2 * num3; std::cout << calculations; }

Specifying types would help us understand code better and find what's wrong:

cpp

main

copy
1234567891011
#include <iostream> int main() { float num1 = 9; float num2 = 12; float num3 = 15000; float calculations = num1 / num2 * num3; std::cout << calculations; }

Note

Any of num1, num2 or num3 should be float to output the correct result.

Nevertheless, auto is widely used in range-based for loops since it is a versatile method of iterating over arrays and other containers. Just use the following syntax for iterating over arr:

cpp

main

copy
123456789
#include <iostream> int main() { int num_arr[5] = {1, 5, 10, 15, 20}; for (auto num : num_arr) std::cout << num << " "; }

It also can be used when the type is long to type but is clear from the context and can't lead to incorrect results.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 4
some-alt