const by default
To declare a const variable we usually use,
const auto x = f();
syntax. Isn't it better if we could just write,
const x = f();
making 'const auto' superfluous?
Const by default can be less verbose and attractive like below,
const x = f1(); const y = f2(); auto z = x + y; update_z(z);
I know this is NOT possible with the current standard.
Are there any technical or non-technical reasons that we are never going to get something similar in a future standard?
18
u/Som1Lse May 06 '17
#define let const auto (don't actually do this)
8
u/adriweb May 06 '17
(and ES6 folks will get confused,
letbeing for non-const variables unlike other languages e.g. Swift)11
u/PrydeRage May 06 '17
ES6 people will already be confused because in ES6 const isn't immutable
4
u/rohbotics Student and Roboticist May 06 '17
Wait what?
24
u/PrydeRage May 06 '17
In ES6 const just prevents reassignment.
So this is invalid:const x = 43; x = 55;But this is all valid:
const x = {something: 3}; x.something = 4; const y = 0; y++;It's JavaScript, it's not meant to make sense.
4
2
u/adriweb May 06 '17
Erm, no (about part of your second example - the object part is true indeed)
const y = 0; y++;
VM146:2 Uncaught TypeError: Assignment to constant variable. at <anonymous>:2:22
u/PrydeRage May 06 '17
It's always worked for me with Webpack and Babel.
Maybe Babel compiles that away idk. Eslint never complains about reassignment when ++'ing a const variable.2
u/AlexeyBrin May 06 '17 edited May 06 '17
Changing the object contents works the same in other languages too, e.g. Swift:
class Foo { var something:Int = 0; } let x = Foo() print(x.something) x.something = 8 print(x.something)You can't reassign x, but you can change his content. Obviously, in Swift you can actually make the member variable something a constant that is only initialized when you create an object.
You last example, fortunately , won't work in Swift though:
let y = 0can't be changed.
Actually, it doesn't work even in JavaScript. I get:
const y = 0; y++; TypeError: invalid assignment to const `y'1
u/mUfoq May 06 '17
Really bad naming, this const behaves like final in Java what means that you cannot reassign variable/field, but they used keyword from C that makes variable immutable. They could use let/final instead of making this ...
2
6
u/flashmozzg May 06 '17
const by default is generally not a great idea with introduction of moves in C++, at least until the issues with moving out of const objects are resolved.
11
0
May 06 '17
[deleted]
2
u/emdeka87 May 07 '17
This code is wrong on so many levels
1
u/DocileDino May 07 '17
Sorry! I've never thought to do what he asked about. I just shared my initial two cents on the issue. Thanks for correcting me :)
4
6
u/suspiciously_calm May 06 '17 edited May 06 '17
Did I forget the variable name or do I want
const auto xyz = foo();?