0

Hello,
Can someone, please, comment on the following curious fact that I encountered in C (actually, I use gcc, which has the default language Gnu C): If one writes

const int a=10;
const int b=a;

one gets an error indication at the declaration of b (not constant!). I would be particularly interested in knowing whether there is a way of getting around this (i.e. declaring a const with a previously declared const). I was actually surprised by this since, I think, C++ allows it.
Regards,
bostjanv

4
Contributors
7
Replies
27
Views
2 Years
Discussion Span
Last Post by bostjanv
0

Off the top of my head, the C standards don't disallow that code in any way. Further, my tests with gcc don't mesh with your results. Please post a complete compilable example and the full compiler output including your instantiation of gcc.

0

Thanks for your reply. Here are my results. I'm using gcc 4.7.2 on Debian 7

0

Thanks for your reply. Here are my results. I'm using gcc 4.7.2 on Debian 7. I ran the following file (test.c)

===================================

const int a=10;
const int b=a;

int main(int argc, char *argv[]) {
}

===================================

and the result was as follows:

===================================
bostjan@wwpecker-5-deb:~/workspace/OB2/src$ cc -c -o test.o test.c
test.c:3:1: error: initializer element is not constant

b

I hope I can clear this up.
Regards,
bostjanv

0

Yes, the variable 'a' is const (you cannot change it), but the VALUE of the variable is a standard scalar value, which is not necessarily const. You need to cast the value to a const, as in:

const int b = (const int)a;

I agree that this should not be required, and it may be a bug in gcc 4.7.2. Have you asked the user forums at GNU for GCC about this?

1

This has nothing to do with const. If you remove the const keyword from your program, you'll get the same error.

The problem is that the initializer for a global variable must be a constant. Confusingly the meaning of the word "constant" here has nothing to do with the const keyword. Here "constant" means either a literal (something like 5, 'c' or "hello") or the application of an operator where all operands are constants. So something like 3 + 5 would be okay, but 3 + x or just x would not be.

Basically the initializer of a global variable must not depend on the value of any other variable or function.

0

Hello,
I checked the suggestion made by rubberman [const int b = (const in)a;], and the result was the same (error). Therefore, the interpretation given by sepp2k is probably right. However, I will verify that in the gcc forum, and reply when I obtain an answer.
Regards,
bostjanv

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.