11-08-2012 03:00 AM
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
Solved! Go to Solution.
11-08-2012 06:58 AM
Hello,
did you tried with '#define' definition rather than 'const int' definition ?
11-08-2012 07:10 AM
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
11-13-2012 10:06 AM
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
11-14-2012 01:24 AM
Thanks!
This explains a little bit more why it's not accepted for ANSI-C.
C++ resolves this which is good...
Regards
Dag