www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Init const fixed-sixed array in ctor

reply bearophile <bearophileHUGS lycos.com> writes:
This is a known bug, right?


struct Foo {
    const char cc;
    const char[1] array;
    this(char c) {
        cc = c;       // OK
        array[0] = c; // Error: this.array[0] isn't mutable
    }
}
void main() {}


Bye,
bearophile
Jun 17 2011
parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On 2011-06-17 17:09, bearophile wrote:
 This is a known bug, right?
 
 
 struct Foo {
     const char cc;
     const char[1] array;
     this(char c) {
         cc = c;       // OK
         array[0] = c; // Error: this.array[0] isn't mutable
     }
 }
 void main() {}
You probably have to set the whole array at once. The array's elements _are_ const after all. In every other place that you want to initialize a const or immutable array, you have to do it all at once. I don't see why this would be any different. Sure, it's a special case where setting that one element sets the whole array, but making that work would be special casing for such an array and complicate the compiler for little benefit. Now, if array = [c]; doesn't work, _then_ we have a problem. - Jonathan M Davis
Jun 17 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Jonathan M Davis:

Sure, it's a special case where setting that one element sets 
 the whole array, but making that work would be special casing for such an 
 array and complicate the compiler for little benefit.
Don't worry, I have defined the array of length one just because I like to minimize my examples :-)
 Now, if
 array = [c];
 doesn't work, _then_ we have a problem.
This doesn't compile, nor several variants of it: struct Foo { const char[1] array; this(char c) { array = [c]; } } void main() {} Bye, bearophile
Jun 17 2011
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On 2011-06-17 18:18, bearophile wrote:
 Jonathan M Davis:
 
 Sure, it's a special case where setting that one element sets
 
 the whole array, but making that work would be special casing for such an
 array and complicate the compiler for little benefit.
Don't worry, I have defined the array of length one just because I like to minimize my examples :-)
 Now, if
 array = [c];
 doesn't work, _then_ we have a problem.
This doesn't compile, nor several variants of it: struct Foo { const char[1] array; this(char c) { array = [c]; } } void main() {}
Then that's a problem, since that makes initializing the array dynamically impossible. Definitely worthy of a bug report. - Jonathan M Davis
Jun 17 2011