contract constantState {
uint constant public test = block.number;
}
Every time I call test() I get the current block number. I thought the block number would be written into state during contract creation.
> constantstate.test()
31892
> constantstate.test()
31892
> constantstate.test()
31893
> constantstate.test()
31902
Removing the constant modifier makes it constant.
I suppose constant means "constantly re-evaluated". :stuck_out_tongue_winking_eye:
Thanks for the find! Yeah, constant means don't store this expression in storage but rather re-evaluate it everytime it is used.
On a side note: constant for functions does not mean they are constant, it just means they should not change storage. We have to revisit these keywords at some point.
Does it make sense to have the constant modifier on state variables? Shouldn't the memory keyword do what constant is doing for state variables?
@axic you cannot combine memory with uint, it's a different thing than constant. We should check if the expression that is assigned is actually constant. We could also use a different keyword like inline because that is actually what is happening.
@chriseth I've collected my thoughts in #992
Based on #992, this is considered a bug.
Question to think about: Should the following be valid after the change?
contract C {
function (uint) returns (uint) constant x = f;
function f(uint) returns (uint) {}
}
The value of the variable x is a compile-time constant, so I would say yes.
... although I did not implement that for now.
I found really useful to use constant expressions. Maybe we could change constant keyword to expression or volatile.
Example:
contract LockableCoin is AbstractCoin {
//creation time, defined when contract is created
uint public creationTime = now;
//time constants, defines epoch size and periods
uint public constant UNLOCKED_TIME = 25 days;
uint public constant LOCKED_TIME = 5 days;
uint public constant EPOCH_LENGTH = UNLOCKED_TIME + LOCKED_TIME;
//current epoch constant formula, recalculated in any contract call
uint public constant CURRENT_EPOCH = (now - creationTime) / EPOCH_LENGTH + 1;
//next lock constant formula, recalculated in any contract call
uint public constant NEXT_LOCK = (creationTime + CURRENT_EPOCH * UNLOCKED_TIME) + (CURRENT_EPOCH - 1) * LOCKED_TIME;
(...)
}
Most helpful comment
I suppose constant means "constantly re-evaluated". :stuck_out_tongue_winking_eye: