473,836 Members | 1,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const problem

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;
char ac[MAXSIZE] = "abc";
char *pc;

for( pc = ac; *pc != '\0'; ++pc )
{
printf("%c\n", *pc);
}
return EXIT_SUCCESS;
}

============ OUTPUT ==============
[arnuld@raj C]$ gcc -ansi -pedantic -Wall -Wextra test.c
test.c: In function `main':
test.c:8: warning: ISO C90 forbids variable-size array `ac'
test.c:8: error: variable-sized object may not be initialized
[arnuld@raj C]$

K&R2 section 2.4, says:

"For an array, the const qualifier says that elements will not be
altered."

but I can't even compile the program.


[arnuld@raj C]$ gcc --version
gcc (GCC) 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is
NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.

--
http://lispmachine.wordpress.com/

Please remove capital 'V's when you reply to me via e-mail.

Jun 27 '08 #1
16 1931
arnuld wrote:
I have declared an int as const but compiler still says that it is not a
const:
[...]
This is Question 11.8 in the comp.lang.c Frequently
Asked Questions (FAQ) list, <http://www.c-faq.com/>.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #2
On Mon, 14 Apr 2008 18:12:37 +0500, arnuld wrote:
I have declared an int as const but compiler still says that it is not a
const:
...[SNIP]...
K&R2 section 2.4, says:

"For an array, the const qualifier says that elements will not be
altered."
but I can't even compile the program.


I got it here: http://c-faq.com/ansi/constasconst.html
but I really don't understand the FAQ statement:
" ..... an object so qualified is a run-time object which cannot
(normally) be assigned to. The value of a const-qualified object is
therefore not a constant expression in the full sense of the term,..."
It is read-only at run-time ? I don't understand, can someone please
explain ?

" ........When you need a true compile-time constant,
use a preprocessor #define (or perhaps an enum)"

I prefer using <enumrather than #define. K&R2 use #define all the time.
should I change my style ?


--
http://lispmachine.wordpress.com/

Please remove capital 'V's when you reply to me via e-mail.

Jun 27 '08 #3
arnuld wrote:
I have declared an int as const but compiler still says that it is not a
const:
In C, variables declared const are not constant-expressions.

They just aren't; there are probably good-enough reasons.

(For an int const, you can use an enum.)

--
"What would that matter, if it made a good book?" /Gaudy Night/

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jun 27 '08 #4
"Chris Dollin" <ch**********@h p.comwrote in message
news:ft******** **@news-pa1.hpl.hp.com. ..
arnuld wrote:
>I have declared an int as const but compiler still says that it is not a
const:

In C, variables declared const are not constant-expressions.

They just aren't; there are probably good-enough reasons.

(For an int const, you can use an enum.)
This keeps coming up. Wouldn't it be better to just fix const so that it
works like const in Pascal for example?

I think existing const (==readonly attribute) must be left as it is because
of code that uses pointers to them. Proper consts wouldn't allow pointers to
them at all. So an alternative is needed.

Using #define is not really satisfactory (scope problems and so on). And
using enum is a workaround.

--
Bart
Jun 27 '08 #5
arnuld <ar*****@ippiVm ail.comwrites:
>On Mon, 14 Apr 2008 18:12:37 +0500, arnuld wrote:
>I have declared an int as const but compiler still says that it is not a
const:
>...[SNIP]...
>K&R2 section 2.4, says:

"For an array, the const qualifier says that elements will not be
altered."
>but I can't even compile the program.

I got it here: http://c-faq.com/ansi/constasconst.html

but I really don't understand the FAQ statement:

" ..... an object so qualified is a run-time object which cannot
(normally) be assigned to. The value of a const-qualified object is
therefore not a constant expression in the full sense of the term,..."

It is read-only at run-time ? I don't understand, can someone please
explain ?
[...]

C's "const" doesn't meant "constant"; it means "read-only", which is a
weaker condition. It merely means that you're not allowed to modify
the object after it's been initialized.

In the absence of VLAs (variable-length arrays, a C99-specific
feature), C90 requires a *constant* expression as an array dimension,
such as

int arr[10];

This:

const int not_a_constant = 10;

doesn't create a constant expression, any more than this does:

const int not_a_constant_ either = rand();

The fact that one of these is initialized with a constant expression
makes no real difference, at least as far as the language is
concerned. (The language *could* have been specified so that a const
declaration creates an actual constant if the initializer is a
constant expression, but it wasn't.)

However, the compiler is still allowed to treat ``not_a_constan t'' as
constant *internally*, replacing any reference to it with the value
10. It just can't be used in a context that requires an actual
constant expression.

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #6
"Bartc" <bc@freeuk.comw rites:
"Chris Dollin" <ch**********@h p.comwrote in message
news:ft******** **@news-pa1.hpl.hp.com. ..
>arnuld wrote:
>>I have declared an int as const but compiler still says that it is not a
const:

In C, variables declared const are not constant-expressions.

They just aren't; there are probably good-enough reasons.

(For an int const, you can use an enum.)

This keeps coming up. Wouldn't it be better to just fix const so that it
works like const in Pascal for example?
In theory, yes.
I think existing const (==readonly attribute) must be left as it is because
of code that uses pointers to them. Proper consts wouldn't allow pointers to
them at all. So an alternative is needed.
I don't think pointers would be a problem. For example, C++ did
change the semantics of const. In essence, if an object is declared
"const" and its initializer is a constant expression, then any
reference to the object is a constant expression. This allows things
like this:

const int n = 5;
switch (some_expr) {
case n: /* not allowed in C */
...*/
...
}

while still permitting non-constant const declarations:

const int const_but_not_c onstant r = rand();

One problem with this idea is that, even if it were added in the next
revision of the C standard, it would be many years before you could
count on widespread compiler support. That's not a reason to reject
the idea, but you won't be able to use it any time soon (unless you
switch to C++).

It's also possible that it could break some existing code in ways I
haven't thought of.
Using #define is not really satisfactory (scope problems and so on). And
using enum is a workaround.
Agreed. The enum trick only works for constants of type int, and it's
really not what the "enum" construct was meant for. (Nevertheless,
it's a neat trick, and I wouldn't hesitate to use it.)

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #7
arnuld wrote:
>On Mon, 14 Apr 2008 08:47:59 -0700, Keith Thompson wrote:
>C's "const" doesn't meant "constant"; it means "read-only", which is a
weaker condition. It merely means that you're not allowed to modify
the object after it's been initialized.

object is read only and can't be modified once initialized but then it is
not const which means it is writable :-\
It's not const at *compile* time, but it is at *run* time. Which is why
you can't use a const for an array size (which requires a compile time
constant).
>
>However, the compiler is still allowed to treat ``not_a_constan t'' as
constant *internally*, replacing any reference to it with the value 10.

I am pretty much confused by these statements. It looks like the
C has the same complexity of C++.
With respect to const, C++ actually simplifies the rules. A const is a
compile and run time constant.

It is more that a little daft that a C compiler can replace a const int
with its constant value (at compile time), but can't use that value
(which it knows) where a compile time constant is required.

--
Ian Collins.
Jun 27 '08 #8
On Tue, 15 Apr 2008 17:12:53 +1200, Ian Collins wrote:
It's not const at *compile* time, but it is at *run* time. Which is why
you can't use a const for an array size (which requires a compile time
constant).
This explanation is simple enough to understand :)

With respect to const, C++ actually simplifies the rules. A const is a
compile and run time constant.

and when I 1st learned C++, I was blown away by the complexity of C++
const mechanism. Now it is not so, it was at the beginning.

It is more that a little daft that a C compiler can replace a const int
with its constant value (at compile time), but can't use that value
(which it knows) where a compile time constant is required.

so, in case of #define or enum:

a C compiler can replace a #define/enum with its value
(at compile time), and can use that value (which
it knows) where a compile time constant is required.
right ?

--
http://lispmachine.wordpress.com/

Please remove capital 'V's when you reply to me via e-mail.

Jun 27 '08 #9
arnuld wrote:
>
so, in case of #define or enum:

a C compiler can replace a #define/enum with its value
(at compile time), and can use that value (which
it knows) where a compile time constant is required.
right ?
Right.

--
Ian Collins.
Jun 27 '08 #10

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

Similar topics

3
3621
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
3
2241
by: Steven T. Hatton | last post by:
Sorry about the big code dump. I tried to get it down to the minimum required to demonstrate the problem. Although this is all done with GNU, I believe the problem I'm having may be more general. Someone on the SuSE programming mailing list suggested my problem is that I'm trying to execute a function (I assume he meant the constructor) at compile time. The same source code compile if I don't try to split it up into separate libraries. ...
13
2592
by: Amadeus W. M. | last post by:
I have a member static const int x defined in class Foo, and I'm passing it by reference, and by value elsewhere (see the code below). Passing it by value works, but by reference it doesn't: it thinks x is undefined. Could someone explain what's going on here? Why can't I pass a static const member by reference? This is how I compile it: g++ -g -Wall sample_main.C # g++ -v 4.0.1...
9
2143
by: Alex | last post by:
Hi. I'll try my problem with this example: class C { protected: virtual int* getProtected(int index)=0; public: const int* get(int index) const { return (const int*) getProtected(index); } virtual void set(int index, int value)
5
1643
by: Bit byte | last post by:
I have the following methods: static void Foo::setBar(const Bar*) ; //store a copy of Bar static const Bar* Foo::getBar(void) const ; //return an UNMODIFIABLE ptr to our internal copy In another part of my code , I retrieved and used Bar as follows: .... const Bar* temp = NULL ;
4
6699
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
4
2190
by: developereo | last post by:
Hi folks, Can anybody shed some light on this problem? class Interface { public: Interface() { ...} virtual ~Interface() { ...} virtual method() = 0; };
2
9160
by: nassim.bouayad.agha | last post by:
Hello, here is a code snippet showning my problem : template<typename _K> class TClass1 { public: void Process(const _K& arg) const {
12
6259
by: hweekuan | last post by:
hi, it seems i can't assign the const variable u in class A, one way to solve the problem may be to build a copy constructor. however, why does C++ or vector class not like this code? my g++ is: gcc version 4.0.1 (Apple Inc. build 5465). thanks for the help. summary of compile error: --------------------------------------- cpp.C:4: error: non-static const member 'const unsigned int A::u',
39
2800
by: Leonardo Korndorfer | last post by:
Hi, I'm litle confused by the const modifier, particularly when use const char* or char*. Some dude over here said it should be const char when you dont modify it content inside the function, I read somewhere that it when you won't modify after its initialization... So when exactly do I use one or another? Is it *wrong* not use const when I should?
0
9825
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10553
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...
1
7793
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
6980
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
5651
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...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4021
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
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.