syntax question on "invariant" keyword

BCS ao at pathlink.com
Tue Jul 3 15:23:50 PDT 2007


Reply to Michael,

> I tried an example from
> http://www.digitalmars.com/d/final-const-invariant.html:
> *** begin Test.d ***
> import std.stdio;
> struct S
> {
> int x;
> invariant int y;
> }
> void main() {
> writefln(S.sizeof); // prints 4, not 8
> }
> *** end Test.d ***
> 
> Compilation gives the error message
> Test.d(5): statement expected to be { }, not int
> So I changed the line
> invariant int y;
> into
> invariant {int y;}
> and now the compilation works.
> Why do I need the curly braces here?
> And why does the example not work? Was there a change to the syntax
> rules of "invariant"?
> Tanks in advance,
> 
> ~michael
> 

This is getting into the ambiguity between an invariant function (that is 
part of design by contract) and an invariant value (that is one form of const).

I think the way that it should be done is

invariant(int) y;




More information about the Digitalmars-d-learn mailing list