Jump to content
  • Advertisement
Sign in to follow this  
noatom

Question regarding constants

This topic is 1974 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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() {} ///:~ 

 

 

Share this post


Link to post
Share on other sites
Advertisement

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.

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!