Author Topic: error C2099: initializer is not a constant  (Read 13622 times)

Offline Richard

  • Newbie
  • *
  • Posts: 44
    • View Profile
error C2099: initializer is not a constant
« on: October 05, 2007, 05:49:10 AM »
The following C code
Code: [Select]
const int a=1;
const int b=2;
const int c=a+b;
void main(){}
generates an "error C2099: initializer is not a constant" for the line const int c=a+b; when compiled with Visual C++ 2005 Express Edition (the compiler I use for simulation) but not when compiled with the Freescale CodeWarrior C compiler.
   Is this a bug of the Visual C++ compiler or a non-standard extension of the Freescale compiler?
   I know I could use various #define work arounds, but would prefer not to, for exactly the reasons that const was added to C.  Is there a good way around this?
    Thanks,
        Richly

Offline mark

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 3236
    • View Profile
    • uTasker
Re: error C2099: initializer is not a constant
« Reply #1 on: October 05, 2007, 08:35:54 AM »
Hi Richly

I tend to agree with VS that the c=a+b is not legal code.

I have had various cases where code works in some compilers and not others and usually (if you have  time and energy) it is possible to find the explanation for it in the (ANSI) compiler guidelines. Some cases are not so strickly defined and due to the interpretation capabilities the solution used by certain compiler manufacturers can be different.

In this case CW is a little more 'intelligent' because it is obvious that c=1+2 is what the line is doing, which is obviously legal. But VC is being more strict because it is also true that a value can not be initialised with another variable's value as it is not (necessarily) known at start up.

I would play safe and use the defines as you already suggested.

Regards

Mark

Offline Richard

  • Newbie
  • *
  • Posts: 44
    • View Profile
Re: error C2099: initializer is not a constant
« Reply #2 on: October 06, 2007, 05:26:47 AM »
Thanks.  What I've decided to do is use my hand-calculated value in the case of the Microsoft compiler and then check it using the _ASSERT macro.  It's clumsy, but it guarantees that if the value of a or b is changed, then c must be changed correspondingly.  The resultant code is below.  Note the inclusion of <crtdbg.h>.

Code: [Select]
const int a=1;
const int b=2;

#ifdef _WINDOWS
    const int c=3;
#else
    const int c=a+b;
#endif

#ifdef _WINDOWS
    #include <crtdbg.h>
#endif


void main(){
#ifdef _WINDOWS
    _ASSERT(c == (a+b));
#endif
}