Strange compiler error. Whose bug is that?
Oleksii Skidan
al.skidan at gmail.com
Fri Jan 26 21:17:14 UTC 2018
Hi,
I get a strange error:
```
λ dub build
Performing "debug" build using D:\d\dmd2\windows\bin\dmd.exe for
x86.
strange ~master: building configuration "application"...
source\app.d(24,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][0]
source\app.d(25,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][1]
source\app.d(24,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][1]
source\app.d(25,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][2]
source\app.d(24,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][2]
source\app.d(25,18): Error: non-constant expression
&[Particle(1.00000F, 1.00000F, 1.00000F), Particle(2.00000F,
2.00000F, 1.00000F), Particle(3.00000F, 3.00000F, 1.00000F)][0]
D:\d\dmd2\windows\bin\dmd.exe failed with exit code 1.
```
when compiling the following code:
```
import std.stdio;
struct Particle {
float x;
float y;
float invMass;
this(float x, float y)
{
this.x = x;
this.y = y;
this.invMass = 1f;
}
}
struct Constraint {
Particle* x;
Particle* y;
float distance;
this(ref Particle x, ref Particle y)
{
this.x = &x;
this.y = &y;
auto dx = x.x - y.x;
auto dy = x.y - y.y;
import std.math;
this.distance = sqrt(dx*dx + dy*dy);
}
}
interface Body {
void tick();
}
class Triangle : Body {
Particle[3] particles = [
Particle(1, 1),
Particle(2, 2),
Particle(3, 3)
];
Constraint[3] constraints;
this()
{
constraints[0] = Constraint(particles[0], particles[1]);
constraints[1] = Constraint(particles[1], particles[2]);
constraints[2] = Constraint(particles[2], particles[0]);
}
void tick()
{
particles[0].x += 1;
}
}
struct Game {
Triangle player = new Triangle;
void tick() {
player.tick();
}
}
void main()
{
Game game;
game.tick();
}
```
Is that my bug (highest probability here) or a compiler bug? I'm
confused, since the following `main` function compiles
successfully:
```
void main()
{
Triangle player = new Triangle;
player.tick();
}
```
as well as this code:
```
struct Game {
Triangle player;
this(Triangle player)
{
this.player = player;
}
void tick() {
player.tick();
}
}
Game makeGame()
{
return Game(new Triangle);
}
void main()
{
auto game = makeGame();
game.tick();
}
```
What's wrong with the first code snippet?
Thanks in advance,
--
Oleksii
More information about the Digitalmars-d-learn
mailing list