[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: static const int optimization fails in conditional expressions



On Tue, Dec 11, 2001 at 05:06:31PM -0600, James Jurach wrote:
> When class members declared as static const int appear in conditional
> expressions, they are not properly optimized out.  The compiler treats them
> as undefined variables, rather than integer literals.

That's because they /are/ undefined variables, not integer literals.
Integer literals are 17, 42, and -3, not Foo::erf, regardless of how
unchanging Foo::erf may be.

Static class member variables must always be /defined/.  That means they
must be given a variable definition in one-and-only-one translation unit,
outside the class declaration.  Some compilers will let you get away with
this sloppiness; gcc 3+ will not.


    % cat fixed_condexpr.cc
    #include <iostream>

    struct Foo
    {
      static const int erf = 0;
      static const int foo = 1;
    };

->  const int Foo::erf;
->  const int Foo::foo;

    int main(int argc, char**)
    {
      std::cout << "foo: " << (argc%2 ? Foo::erf : Foo::foo) << std::endl;
      return 0;
    }

    % g++-3.0 -Wall -W fixed_condexpr.cc
    % ./a.out
    foo: 0
    % ./a.out x
    foo: 1
    %

Phil

-- 
If ye love wealth greater than liberty, the tranquility of servitude greater
than the animating contest for freedom, go home and leave us in peace.  We seek
not your counsel, nor your arms.  Crouch down and lick the hand that feeds you;
and may posterity forget that ye were our countrymen.            - Samuel Adams



Reply to: