LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

const compile error

Solved!
Go to solution

Hi

 

If I declare a const value that is based on a prevously declared const I get a compile error:

 

const int MY_INT_CONST1 = 10;  //no error.
const int MY_INT_CONST2 = MY_INT_CONST1 + 10; //compile error: Initializer must be constant

 

I tried to search on the internet to find out if this is against ANSI-C, but didn't find the relevant answer.

Anyone who knows, and have a source of information?

 

Thanks!

dml72

0 Kudos
Message 1 of 5
(3,342 Views)

Hello,

 

did you tried with '#define' definition rather than 'const int' definition ?

 

 

0 Kudos
Message 2 of 5
(3,333 Views)

Hi

 

#define's is not a problem.

 

I just want to understand why the second const declation generates a compile error.

I suspect that it is not according to ANCI C.

 

Can anyone confirm and give a link to useful information?

 

Dag

0 Kudos
Message 3 of 5
(3,329 Views)
Solution
Accepted by topic author dml72

Hello,

As I can remember, in ansi C, global variables must be initialized by constants.
So we can write :
# define MYVAR 5
int a = MYVAR;
because the preprocessor replace MYVAR by 5 before compiling the sources.

But if we write
const int a = 1;
const int b = a;

We want initialise b with the value of a, which is a global variable and the compiler must detect an error (declare a constant variable will generate a compilation error if the variable is reassigned into the program, but it's still a variable, and not a constant).

The same compilation error should appear if we write in the global section

int a = 1;

int b = a;

int c = myFunction ();



However in local sections, initializer does not need to be constant, so we can write

void myfunction (void) {
          const a = 1;
          const b = a;
          const c  = myfunction2 ();
           ...
}

 

In summary, the keyword "const" is not the reason of this error, you can add or remove this keyword, the error will alway be the same.

It is just impossible to initialize a globale variable with another variable because globale variables are initialized before the execution of any instruction.

 

 

Regards

Étienne

 

0 Kudos
Message 4 of 5
(3,291 Views)

 

Thanks!

 

This explains a little bit more why it's not accepted for ANSI-C.

 

C++ resolves this which is good...

 

Regards

Dag

0 Kudos
Message 5 of 5
(3,270 Views)