In C++ 11, we're encouraged to use auto for variable type,
does this also apply when initializing type like class and vector?
I mean should we write the following:
auto a = 10;
auto b = MyClass();
auto c = vector<int>{1, 2, 3};
instead of:
auto a = 10;
MyClass b;
vector<int> c = {1, 2, 3};
C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.
Automatic initialization in Java Java does not initialize non-array local variables (also referred to as automatic variables) . The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.
You can initialize any auto variable except function parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!
auto
is just a handy shortcut to simplify things like
VeryLongClassName *object = new VeryLongClassName();
Now it will be
auto *object = new VeryLongClassName();
There is no reason to write
auto a = 10;
auto b = MyClass();
auto c = vector<int>();
because it is longer and harder to read than
int a = 10;
MyClass b;
vector<int> c;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With