1

I have this code:

class Set(T){
    private T[] values;

    T get(uint i){
        return ((i < values.length) ? T[i] : null);
    }
...

And when I try use this class this way:

set.Set!(int) A;

compiler gives error at the return line: set.d|9|error: variable i cannot be read at compile time

Can somebody explain, what's wrong in my code? Thanks.

5
  • Are you sure that's all the code? Commented Oct 7, 2016 at 15:34
  • 1
    ooh othugh the T[i] line is wrong anyway, T is a type, the array is values Commented Oct 7, 2016 at 15:37
  • 1
    Did you perhaps mean values[i]?
    – rcorre
    Commented Oct 7, 2016 at 15:38
  • Yes, I meant values[i], Thanks!
    – Shadasviar
    Commented Oct 7, 2016 at 15:47
  • does that fix it? if so you can post it as an answer or whatever. Commented Oct 7, 2016 at 18:04

1 Answer 1

0

That is the answer: the code simply referenced the wrong variable. The reason it gave the error it did is that T[i] is trying to get an index out of a compile-time list of types... which needs i to be available at compile time too. However, since i is a regular variable, it isn't. (You can have compile time variables btw - the result of a function may be CT evaled, or the index on a foreach over a static list, or an enum value.) However, what was wanted here was a runtime index into the array... so the values is the right symbol since it is the data instead of the type.

By Adam D. Ruppe

3
  • That is the answer: the code simply referenced the wrong variable. The reason it gave the error it did is that T[i] is trying to get an index out of a compile-time list of types... which needs i to be available at compile time too. However, since i is a regular variable, it isn't. (You can have compile time variables btw - the result of a function may be CT evaled, or the index on a foreach over a static list, or an enum value.) However, what was wanted here was a runtime index into the array... so the values is the right symbol since it is the data instead of the type. Commented Oct 8, 2016 at 0:20
  • That's a truly terrible error message for this particular mistake. Do you have any opinions on whether we can/should special-case this in the compiler @AdamD.Ruppe?
    – Meta
    Commented Oct 13, 2016 at 19:23
  • eh maybe but it would be hard to tell if it was an intentional subscript or not.... well, actually, T here isn't even valid to subscript anyway, so it should probably be a type error with no special casing needed. But if it was T... then this error would probably be right. Commented Oct 14, 2016 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.