473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 1880
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**********@hp.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*****@ippiVmail.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_constant'' 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_Keith) <ks***@mib.org>
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.comwrites:
"Chris Dollin" <ch**********@hp.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_constant 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_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #7
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 :-\
However, the compiler is still allowed to treat ``not_a_constant'' 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++.

It just can't be used in a context that requires an actual constant
expression.

okay, I, finally, think that it is much better idea to not to use const at
all. enum is fine for int constants and #define for everything else.


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

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

Jun 27 '08 #8
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_constant'' 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 #9
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 #10
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 #11
On Tue, 15 Apr 2008 10:44:31 +0500, arnuld <ar*****@ippiVmail.com>
wrote:
snip
>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.
As far as #define is concerned, after the preprocessor gets done
substituting everything, the compiler will never see the #define name,
only the substituted value. Therefore, the compiler *must* use the
substituted value. If the substituted token is a self defining term,
then it can be used where a compile time constant is required.
Remove del for email
Jun 27 '08 #12
On Mon, 14 Apr 2008 09:04:49 -0700, Keith Thompson <ks***@mib.org>
wrote:
<snip>
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
including a 'static' (classwide) data member
"const" and its initializer is a constant expression, then any
and of an integer or enumeration type (in C++ enum types are distinct,
not just aliases for integer types as they are in C)
reference to the object is a constant expression. This allows <snip>
But most of the places C (or C++) requires a constant expression do
require integer (constant expression), including the example you gave
of a case label, and this feature is enough for those.

- formerly david.thompson1 || achar(64) || worldnet.att.net
Jun 27 '08 #13
David Thompson wrote:
On Mon, 14 Apr 2008 09:04:49 -0700, Keith Thompson <ks***@mib.org>
wrote:
<snip>
>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

including a 'static' (classwide) data member
>"const" and its initializer is a constant expression, then any

and of an integer or enumeration type (in C++ enum types are distinct,
not just aliases for integer types as they are in C)
>reference to the object is a constant expression. This allows <snip>

But most of the places C (or C++) requires a constant expression do
require integer (constant expression), including the example you gave
of a case label, and this feature is enough for those.
Which feature?

--
Ian Collins.
Jun 27 '08 #14
I have always found that using const is only a choice rather than a
necessity. But this is just my opinion, I'm sure the experts here will
differ.

Jun 27 '08 #15
pereges wrote:
I have always found that using const is only a choice rather than a
necessity.
Yes. Most things in life are just choices.
But this is just my opinion, I'm sure the experts here will
differ.
The point of const (in C) is to help the compiler to do more checks on
your source. Consider this trivial program:

#include <stdio.h>

int main(void) {

long double pi = 3.1415926535897932384626433832795029L;
long double r;

puts("Enter radius of circle:");
scanf("%Lf", &r);
printf("Area of the circle is: %Lf\n", pi * (r * r));
return 0;
}

Now imagine this as a part of a much larger program or function.
Obviously 'pi' holds the value of a constant and should not be changed.
However if some other code in your program happens to modify 'pi' your
compiler will silently accept the modification and your program will
start giving you wrong or inaccurate results. This is where
qualifying 'pi' with const will start paying off. Now anywhere a direct
change is made to 'pi' the compiler will give you a diagnostic warning
you of it, so you can correct the code and prevent undefined behaviour.

As someone else said, const may appear rather meritless for small,
one-man programs, but it will start paying dividends when the program
grows larger and is developed by a team, even in spite the quirkiness
of C's const.

PS. You can still attempt to write to a const object and evade compiler
warnings by writing through a pointer, but that's far less likely to
happen in real code than direct in-advertant modification.

Jun 27 '08 #16
On Mon, 28 Apr 2008 15:52:17 +1200, Ian Collins <ia******@hotmail.com>
wrote:
David Thompson wrote:
On Mon, 14 Apr 2008 09:04:49 -0700, Keith Thompson <ks***@mib.org>
wrote:
<snip>
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
including a 'static' (classwide) data member
"const" and its initializer is a constant expression, then any
and of an integer or enumeration type (in C++ enum types are distinct,
not just aliases for integer types as they are in C)
reference to the object is a constant expression. This allows <snip>
But most of the places C (or C++) requires a constant expression do
require integer (constant expression), including the example you gave
of a case label, and this feature is enough for those.
Which feature?
The feature of C++ that Keith described and I slightly corrected, that
a const variable(!) of integer or enum type initialized by a constant
expression is acceptable in a constant expression. (And the which, or
something like it, the upthread discussion suggested for C.)

- formerly david.thompson1 || achar(64) || worldnet.att.net
Jun 27 '08 #17

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

Similar topics

3
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...
3
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. ...
13
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...
9
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); } ...
5
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...
4
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 =...
4
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
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
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:...
39
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...

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.