Skip to main content
GameDev.net gamedev.net
🔒 Locked

Question regarding constants

Started by noatom Apr 27, 2013 at 3:28 PM 2 replies 900+ views
Original Post
noatom
noatom

Can someone please explain why the following code won't work?


const int i[] = { 1, 2, 3, 4 }; 
//! float f[i[3]]; // Illegal 
struct S { int i, j; }; 
const S s[] = { { 1, 2 }, { 3, 4 } }; 
//! double d[s[1].j]; // Illegal 
int main() {} ///:~ 
Paradigm Shifter
Paradigm Shifter

The compiler isn't smart enough. (EDIT: Also, some shenanigans involving const_cast [EDIT2: or a C-style cast, which trumps everything] in global constructors of objects may be able to change the data).

constexpr (C++11) may be able to do that though, depending on whether your compiler supports it yet.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
noatom
noatom

in my book it goes like this: the compiler is not required to know the contents of the storage at compile time.

Based on some tests I did,this doesn't a apply because the array if a const one,but the above rule applies to all arrays.

Please correct me if I'm wrong.

Kylotan
Kylotan
The fact that the array on line 1 is constant, doesn't mean that the statement on line 2 is able to parse that expression.

Remember that an array access (eg. x[3]) is basically treating x as a pointer, then moving it 3 x sizeof(x), and grabbing whatever is at that point. But at compile time, x doesn't have an address. Nothing has an address until after everything is compiled, or in some cases not until run time. So the expression doesn't work.

It's certainly theoretically possible to perform this operation, as you can see. But the compiler simply doesn't make the attempt to interpret the array access in that way.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.