Code behaves incorrectly if it is compiled in std.functional
Artur Skawina via Digitalmars-d
digitalmars-d at puremagic.com
Sun Jun 7 11:44:11 PDT 2015
On 06/07/15 18:49, Timon Gehr via Digitalmars-d wrote:
> This is valid C:
>
> int main(){
> const auto int x=2;
> return 0;
> }
>
> This is not valid C:
>
> int main(){
> auto auto int x=2;
> return 0;
> }
>
> What is the problem?
The problem is the apparently common misunderstanding that
'auto' is a thing in D. It is not; it's just a grammar hack.
The (very simplified) rule for declarations in C/C++/D is
<storage_class> <type> lhs = rhs
In C, you can omit the /storage_class/ and it then defaults to
'auto'. Obviously, the 'auto' keyword is redundant and nobody
actually uses it.
In D, you can omit the /type/ and it's then propagated from the
/rhs/ expression. The compiler already knows the type that 'rhs'
evaluates to.
But you can not omit both the /type/ and the /storage_class/ as
'lhs=rhs' would be indistinguishable from an assignment. In some
contexts for the compiler, but, more importantly, for the human.
Hence 'auto lhs = rhs'.
[The exceptions are either because of backward C compatibility
(function args) or no need for such compatibility (foreach)]
Still, 'auto' isn't as bad as 'static', which D redefined to mean
something different than in C/C++, and did this so subtly that
the C version will still compile, giving unexpected results without
even a warning.
artur
More information about the Digitalmars-d
mailing list