473,624 Members | 1,999 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const and 'constant expression'

Hi C experts

I've a bunch of questions.

Consider this simplified piece of code.

const int a = 10;

int main () {
static int b = a;
return b;
}

~>gcc test.c
test.c: In function `main':
test.c:4: error: initializer element is not constant
~>

Question1
I understand that const is 'read-only' but I could not convince my
co-worker that its value can change.

6.7.8 Initialization

[...]

[#4] All the expressions in an initializer for an object
that has static storage duration shall be constant
expressions or string literals.

Can someone point me to text that says that 'const' is not 'constant
expression' and can in fact change?

He claims that the compiler may choose to substitute the value at
compile time.
I tried to explain how the value can change (but I had to use pointers
to const int) which he shot down saying the comparison of examples is
not valid (it's not initializer and it involves pointers).

Question2
Moreover, if we turn on optimization, (and assume that the real code
does not have any dead code like above), the compiler does not give any
error. Is the compiler correct after optimisation?
I think it is a bug in compiler but I need text in standard to prove
that.

Thanks in advance for your comments
-Dev

Apr 19 '06 #1
13 2560
de**********@ya hoo.com <de**********@y ahoo.com> a écrit*:
I've a bunch of questions.
Consider this simplified piece of code.

const int a = 10;
int main () {
static int b = a;
return b;
}

~>gcc test.c
test.c: In function `main':
test.c:4: error: initializer element is not constant
~>

Question1
I understand that const is 'read-only' but I could not convince my
co-worker that its value can change.


#include <stdlib.h>
#include <assert.h>
int main(int argc, char *argv []) {
assert( argc > 0 );
const int a= atoi(argv[1]);
static int b= a;
return b;
}

Marc Boyer
Apr 19 '06 #2
de**********@ya hoo.com wrote:
const int a = 10;

int main () {
static int b = a;
return b;
}

~>gcc test.c
test.c: In function `main':
test.c:4: error: initializer element is not constant
~>

Question1
I understand that const is 'read-only' but I could not convince my
co-worker that its value can change.
Whether or not it can is of no import to that error. It is not a
constant, as defined by the Standard. That's all that matters.
<http://c-faq.com/ansi/constasconst.ht ml>.
6.7.8 Initialization

[...]

[#4] All the expressions in an initializer for an object
that has static storage duration shall be constant
expressions or string literals.

Can someone point me to text that says that 'const' is not 'constant
expression' and can in fact change?
Any object, whether const or not, is not a constant expression: 6.6.
"Can in fact change": immaterial.
He claims that the compiler may choose to substitute the value at
compile time.
He may claim whatever he wants. It remains a const object, not a
constant expression, and is therefore not a portable initaliser.
Moreover, if we turn on optimization, (and assume that the real code
does not have any dead code like above), the compiler does not give any
error. Is the compiler correct after optimisation?


By 6.6#10, yes. However, no other compiler (nor even the same compiler
the next time) is required to accept its extensions.

Richard
Apr 19 '06 #3
Thanks Marc, point noted.

Now getting back to my example,

const int a = 10;

In this case, can value of 'a' change? If so how?
If not, why can not variable 'a' be treated a compile time constant.

-Dev

Apr 19 '06 #4
Le 19-04-2006, de**********@ya hoo.com <de**********@y ahoo.com> a écrit*:
Thanks Marc, point noted.

Now getting back to my example,

const int a = 10;

In this case, can value of 'a' change?
Not to my knowledge.
If so how?
If not, why can not variable 'a' be treated a compile time constant.


It 'can' in this case. But, just try to explain in wich case
it can and when it can not....

Marc Boyer
--
Si tu peux supporter d'entendre tes paroles
Travesties par des gueux pour exciter des sots
IF -- Rudyard Kipling (Trad. Paul Éluard)
Apr 19 '06 #5
If the compiler can treat this 'a' as a compile time constant then this
should also work

const int size = 5;
int array[size];

But seems like it does not compile even with optimizations.

This is causing confusion.

-Dev

Apr 19 '06 #6
Marc Boyer wrote:

Le 19-04-2006, de**********@ya hoo.com <de**********@y ahoo.com> a écrit :
Thanks Marc, point noted.

Now getting back to my example,

const int a = 10;

In this case, can value of 'a' change?


Not to my knowledge.


Isn't this legal?

==========

#include <stdio.h>

const int a = 10;

int main(int argc,char *argv[])
{
int *pt = (int *)&a;

printf("%d\n",a );

*pt = 20;

printf("%d\n",a );
}

==========

It fails here, at runtime, but only because "a" has been placed into
read-only memory on this platform. But it's perfectly "legal" C, as
far as I know. It compiles without even a warning about "pt" and "a",
even with maximum warnings turned on.

[...]

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Apr 19 '06 #7
de**********@ya hoo.com wrote:
If the compiler can treat this 'a' as a compile time constant then
this should also work


Please read the information below.

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Apr 19 '06 #8
Kenneth Brody wrote:
Isn't this legal?

==========

#include <stdio.h>

const int a = 10; int *pt = (int *)&a; It fails here, at runtime, but only because "a" has been placed into
read-only memory on this platform. But it's perfectly "legal" C, as
far as I know. It compiles without even a warning about "pt" and "a",
even with maximum warnings turned on.


What do you mean by "legal"? It doesn't require a diagnostic, but it's
undefined behavior.

Brian
Apr 19 '06 #9
de**********@ya hoo.com wrote:

Please provide context when replying. Usenet is not Google Groups,
Google Groups is merely on of many Usenet service provides that provides
a poor interface. There is no guarantee that others have (or ever will)
see the post you are replying to.
If the compiler can treat this 'a' as a compile time constant then this
should also work

const int size = 5;
int array[size];

But seems like it does not compile even with optimizations.

This is causing confusion.


Basically, you can't do it because the standard says you can't. const in
C is a promise that you will not attempt to modify something, it does
not declare a real constant. So, for example, you can do:
volatile const int fred;
Then, you might be able to use some magic in your linker to map fred
over a hardware register and each time you read it you will get the
current contents of that register.

Note that C99 added variable length arrays, so in C99 you could do:
int main(void)
{
const int size = 5;
int array[size];
/* do stuff */
return 0;
}

However, in the above array is a variable length array where the length
is determined at run time, not a normal fixed length array.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Apr 19 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
2410
by: Ben | last post by:
For many times, I've found myself changing my member variables from const back to non-const. No matter how good the original objective was, there was always at least one reason not to use const members. (swap, storing it in a container, etc.) Whereas in Java, 80% of the case, I would want "final" for my instance variables. It makes me think that is "const member variable" ever useful in C++? Maybe because of the value semantics of C++...
16
41757
by: herbertF | last post by:
Hi guys, In a program (not my own) I encountered the declaration of a constant pointer to an array consisting of two other const pointers to arrays. Not quite sure why they do it so complicated, but is it legal? Most compilers accept it, but one doesn't recognize the rhs as a constant. What are the requirements for the rhs in the declaration of a const pointer? Is the following program legal C? int main(int argc, char *argv) {
9
2615
by: sarathy | last post by:
Hi, Can anyone just help me with what exactly is constant expression. I read the section on Constant expression in K&R2. i am not fully clear with it.
4
3296
by: Rui.Hu719 | last post by:
Hi, All: I read the following passage from a book: "There are three exceptions to the rule that headers should not contain definitions: classes, const objects whose value is known at compile time, and inline functions are all defined in headers. " Can someone explain to me why some of the const objects must be defined in the header file?
10
2774
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
4
3075
by: jaime | last post by:
Hi again all. Given the line: const int x=5; Can I then use "x" as a constant expression? (By "constant expression", I mean "constant expression" as defined in the C99 standard) I've been searching google for 2 days now trying to answer this myself, and I'm just getting more and more confused (some things I read make me think "yes", while some things I read make me think "no").
10
5949
by: Stephen Howe | last post by:
Hi Just going over some grey areas in my knowledge in C++: 1) If I have const int SomeConst = 1; in a header file, it is global, and it is included in multiple translations units, but it is unused, I know that it does not take up storage in the
7
230
by: abendstund | last post by:
Hi, I have the following code and trouble with ambiguity due to operator overloading.. The code is also at http://paste.nn-d.de/441 snip>>
16
1906
by: arnuld | last post by:
I have declared an int as const but compiler still says that it is not a const: include <stdio.h> #include <stdlib.h> int main() { const int MAXSIZE = 100;
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8624
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7164
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1485
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.