C++ static integer class constants...

Alex J. Dam alexjdam@gmail.com
Sun Oct 16 17:43:00 GMT 2005


On Sun, Oct 16, 2005 at 11:42:48AM -0500, John Ratliff wrote:
> I don't see anywhere that I'm taking the address of A or B. I don't see why
> they should need storage space here. Am I doing something wrong in my
> program?

After reading Ryan's post, I looked at the (draft) standard.  It says:

4 If  a  static  data  member  is of const integral or const enumeration
  type, its declaration in the class definition can specify a  constant-
  initializer   which   shall   be   an   integral  constant  expression
  (_expr.const_).  In that case, the member can appear in integral  con-
  stant expressions within its scope.  The member shall still be defined
  in a namespace scope if it is used in the program  and  the  namespace
  scope definition shall not contain an initializer.

If I understand this correctly, even const static members need to have
a definition somewhere.  Maybe this is "needed" so that you may always
take the address of such const static members.

So the compiler is free to use the constant as if they were variables,
if it needs to.  Your code compiles OK if the line

        int offset = (redundant ? B : A);

is replaced by

        if(redundant)
          offset = B;
        else
          offset = A;

I don't know why, but it does work here.

So you need to define those constants somewhere, but the compiler  may
use the initializer in the class scope, if it is able to do so.  For
some reason, GCC couldn't use the initializer in the first case, so it
is using the address of the constants.  Go figure.

-- 
Alex J. Dam



More information about the Gcc-help mailing list