expected constant expression?

Printable View

• 05-07-2012
GroogFish
expected constant expression?
Hello, newbie here.

Just started euler problems to get better acquainted with C. The first problem is this-

Quote:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
So here is my program-

Code:

```#include <stdio.h> int main() {         int _MAX = 1000;         int nums[_MAX] = {0};         int checkers[] = {3,5};         int k = 0;         int len = sizeof(checkers)/sizeof(int);         int sum = 0;         int checker;         for(k = 0; k < len; k++)         {                 checker = checkers[k];                 sum = 0;                 while(sum+checker <= _MAX)                 {                         sum += checker;                         nums[sum] = 1;                 }         }         sum = 0;         for(k = 0; k < _MAX; k++)         {                 if(nums[k])                         sum += k;         }         printf("%d", sum);         getchar();         return 0; }```
This compiles with an error-

main.c(6): error C2057: expected constant expression
main.c(6): error C2466: cannot allocate an array of constant size 0

which is line

Code:

`int nums[_MAX] = {0};`
If I change _MAX here to 1000 everything works and I get the right answer. What is wrong and how do I fix this? I tried google but got more confused.
• 05-07-2012
phantomotap
o_O

Due what it says on the label: make `_MAX' a constant value.

Soma

http://cboard.cprogramming.com/proje...ml#post1105469
• 05-08-2012
iMalc
It means that you're using a C compiler that is not C99 compliant, and from the looks of it, it's some version of MSVC. MSVC is good for C++, but not so good for C.
If you want to MSVC, use an enum or #define for the size.
Otherwise, others will suggest better C compilers such as "Pelles C".
• 05-08-2012
anduril462
Also, you should not use a leading underscore in your identifiers:
[quote="C99 7.1.3p1]
All identifiers that begin with an underscore and either an uppercase letter or another
underscore are always reserved for any use.
[/code]
It's not likely, but entirely possible, that later on, some implementation you use defines _MAX, and your code no longer works. And pray they don't declare _MAX as a function macro, because it may throw some nasty compiler errors that make no sense when you go back and look at the code.

EDIT: Actually, with a name like _MAX, it's quite likely that an implementation will define it, to be used in calculating the greater of two variables:
Code:

`#define _MAX(a,b)    a > b ? a : b  // yes, I know this is naive and error prone, it's just for demonstration`