By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,383 Members | 2,067 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,383 IT Pros & Developers. It's quick & easy.

When to use const modifier?

P: n/a
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?

thanks in advance.
Leonardo.
Jun 27 '08 #1
Share this Question
Share on Google+
39 Replies


P: n/a
Leonardo Korndorfer wrote:
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...
Both.
So when exactly do I use one or another? Is it *wrong* not use const
when I should?
Not using const is only a problem when the object is a real constant,
like a string literal.

I other cases, const expresses an intent.

--
Ian Collins.
Jun 27 '08 #2

P: n/a
Leonardo Korndorfer wrote:
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,
Const qualifying a function parameter will help the compiler diagnose
any attempt to modify the concerned object within the function.
I read somewhere that it when you
won't modify after its initialization...
The behaviour is the same here.
So when exactly do I use one or another?
That depends on how the object will be used. If the object will only be
initialised and not modified thereafter then you can const qualify it's
declaration. If OTOH you want only certain functions to not modify an
array object, you can const qualify the relevant parameter. This way
other functions can still modify the array. An alternative is to wrap
the array inside a structure before passing it to the function. But
this will not help you catch inadvertent modifications, which is the
main use of const.
Is it *wrong* not use const
when I should?
No. But it's helpful to take advantage of language features to make your
job easier.

Jun 27 '08 #3

P: n/a
Ian Collins wrote:
Leonardo Korndorfer wrote:
>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...
Both.
>So when exactly do I use one or another? Is it *wrong* not use const
when I should?
Not using const is only a problem when the object is a real constant,
like a string literal.
Are string literals "real constants", whatever that means? I thought you
were just supposed to pretend that they were constants, and treat them
as such, to prevent the wrath of UB.

Jun 27 '08 #4

P: n/a
santosh wrote:
Ian Collins wrote:
>Leonardo Korndorfer wrote:
>>I'm litle confused by the const modifier, particularly when use const

Are string literals "real constants", whatever that means? I thought you
were just supposed to pretend that they were constants, and treat them
as such, to prevent the wrath of UB.
Here, C's subtle goals for portability surface. Some memory pages are
marked read-only. Any attempted write to a read-only page by a user mode
program [contrasted with supervisor mode running the OS's kernel] will
result in an interrupt raised by the Memory Management Unit [MMU], the
part of the CPU that translates virtual addresses to physical addresses.
This interrupt notifies the kernel your program is behaving badly. The
default behavior in this case is an abrupt termination known as a "core
dump."

Executable files produced by modern linkers are partitioned into
segments. The ".data" segment is expected to be read-only and *may* be
mapped to a read-only page in virtual memory. Attempting to write it
results in the above behavior. This is the meaning of "real constant":
the hardware and OS will not permit you to write it after the loader
brings that segment into memory and protects the page. String literals
are typically placed in the ".data" segment, so treat them as "real
constants."

This differs somewhat from use of the 'const' keyword. When const is
used in a variable definition, the compiler typically attempts to infer
its value. If the compiler can guess the initial value at compile time,
and by definition the variable's value cannot change after
initialization, then it may optimize the value away. That is, replace
all instructions loading that variable with load-immediate instructions.
If you attempt to take the address of that variable, or the compiler
chooses not to get rid of it, it may place that value in the ".data"
segment again resulting in a "real constant."

You may implicitly cast a non-const to const. Depending on how you
structure your program, you may know that, by design, some function
should not have reason to modify its data. You may declare that data
const to express this fact. Because the compiler knows that nothing will
attempt to modify the data when the particular function is called, all
sorts of optimization trickery becomes possible. The function may be
executed concurrently with others, an OpenMP compiler may spawn separate
threads, VLIW compilers may issue multiple instructions with correct
knowledge that no data dependencies exist, and so on.

Given a constant variable, you may cast away the const property and then
write to it. This is only guaranteed to work if you are certain that the
variable was defined as nonconst. The following example illustrates the
difference between "real constant" and "not as constant as it seems."

void modify(const int *p_a) {
*((int *)p_a) = 7; // take life into own hands; hope caller
// knew what s/he was doing
}

int main() {
int a = 5;
const int b = 5;

modify(&a); // ok: passing the address of a non-const int

modify(&b); // bad: passing the address of a const int.
// Results undefined.

return 0;
}

The first call to modify() works because modify()'s body correctly
assumes that it has really received a pointer to a non-const int. The
second call is likely to fail because that assumption is incorrect.

The author of the modify() function is making some pretty bold
assumptions about the caller and is lying about it in its parameter
list. That's not advised.

Hope this clarifies things.

--
Andrew Kerr
Jun 27 '08 #5

P: n/a
In article <48**************@gatech.edu>,
Andrew Kerr <ar****@gatech.eduwrote:
>Here, C's subtle goals for portability surface. Some memory pages are
marked read-only. Any attempted write to a read-only page by a user mode
program [contrasted with supervisor mode running the OS's kernel] will
result in an interrupt raised by the Memory Management Unit [MMU], the
part of the CPU that translates virtual addresses to physical addresses.
This interrupt notifies the kernel your program is behaving badly.
These things are -commonly- true, but none of them are -necessarily-
true: it is valid for C to run on systems that function quite differently.
>The
default behavior in this case is an abrupt termination known as a "core
dump."
Is that a new behaviour in C99? I can't find any reference to it
in C89, not even in the Rationale.

>Executable files produced by modern linkers are partitioned into
segments. The ".data" segment is expected to be read-only and *may* be
mapped to a read-only page in virtual memory.
And for the systems that do not use "segments", or which do
not have a ".data" segment? Do you simply define those away as
not having "modern linkers" ?
--
"Eightly percent of the people in the world are fools and the
rest of us are in danger of contamination." -- Walter Matthau
Jun 27 '08 #6

P: n/a

"Leonardo Korndorfer" <le***********@gmail.comwrote in message
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?
Use const when you don't modify the string (or other thing pointed to)
within the function. constness only applies within the function's scope.
Outside the variables can be modified, and in fact usually are modified.
Only rarely is data provided in read-only arrays typed into the program
directly.

There's a bit of debate about the virtues of const. One problem is const
poisoning. Once a pointer becomes const, everything it touches has to be
const. Another problem is that constness applies only to the object directly
pointed to. However frequently structures contain other pointers, and you
want to const them as well.
So it is not exactly wrong to avoid const. Personally I try to keep it to a
minimum. However if I am writing code to publish on my website const will
usually be included for a constant pointer parameter that the user provides.
If the pointer parameter is returned by another function in the same file,
however, I usually won't declare it const.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Jun 27 '08 #7

P: n/a
Malcolm McLean wrote:
>
"Leonardo Korndorfer" <le***********@gmail.comwrote in message
>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?
Use const when you don't modify the string (or other thing pointed to)
within the function. constness only applies within the function's scope.
Outside the variables can be modified, and in fact usually are modified.
Only rarely is data provided in read-only arrays typed into the program
directly.
If this means something, I think it must mean something wrong.
A const-qualified object is const-qualified, period, whether it is
in or out of scope. An attempt to modify a const-qualified object
by name or via a const-qualified pointer requires the compiler to
issue a diagnostic; an attempt to modify it by other means yields
undefined behavior. Scope has naught to do with it.
There's a bit of debate about the virtues of const. One problem is const
poisoning. Once a pointer becomes const, everything it touches has to be
const.
Perhaps you should explain what you mean by "touches." If
you mean "points at," the claim is wrong: It is entirely all
right for a pointer-to-const-Thing to point at a Thing that is
not const-qualified.
Another problem is that constness applies only to the object
directly pointed to. However frequently structures contain other
pointers, and you want to const them as well.
What do you mean by "to const?" Is it anything like
"to int" or "to static?"
So it is not exactly wrong to avoid const. Personally I try to keep it
to a minimum.
I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
However if I am writing code to publish on my website
const will usually be included for a constant pointer parameter that the
user provides. If the pointer parameter is returned by another function
in the same file, however, I usually won't declare it const.
This may be an accurate description of your habits, but I
can't see any reason for using or not using `const' based on
which translation unit a function inhabits.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #8

P: n/a
On Jun 2, 8:11*pm, Leonardo Korndorfer <leokorndor...@gmail.com>
wrote:
So when exactly do I use one or another? Is it *wrong* not use const
when I should?

My motto is to use const WHENEVER you can... unless the const is
redudant. The one sole example of it being redundant -- that I'm aware
of -- is its use in casts:

printf("%d",(int const)x);

Other than that one sole example, I use const EVERYWHERE that I can.

Here's how variable definitions work in C:

Type variable_name;

An example would be:

int val;

If you want the variable to be const, then you add const to the
_type_; it doesn't matter whether you put it first or second, these
two are identical:

int const val = 5;
const int val = 5;

Now, if you want to turn a variable into a pointer, then you add an
asterisk to the variable's _name_:

int *val;

If you want the pointer to be const, then you add const to the _name_,
and it always goes AFTER the asterisk:

int *const val;

From there, you can add constness to the "pointed-to type" by adding
const to the type name. Again, it doesn't matter whether the const
comes before or after the type name:

int const *const val;
const int *const val;

A few random examples would be:

int *const val;
const int *val;
int const *val;
int *val;

Remember, white space means nothing in C, so you could see these as:

int* const val;
int*const val;
const int* val;
int const*val;
int* val;
int*val;

Just remember that the asterisk always goes with the _name_, and if
the pointer itself is const then you'll always see the const in the
_name_ and it will always be after the asterisk:

int *const val;
int*const val;
int* const val;

And then you might see something like:

int const* const *const * * * const **p;

p is a
pointer to
pointer to
const pointer to
pointer to
pointer to
const pointer to
const pointer to
const int

Of course you could change the white space:

int const*const*const***const**p;

The only other change you can make to it, without actually changing
the type, is changing the "int const" to "const int" because they're
identical:

const int *const*const***const**p;
Jun 27 '08 #9

P: n/a
Andrew Kerr <ar****@gatech.eduwrites:
santosh wrote:
>Ian Collins wrote:
>>Leonardo Korndorfer wrote:
I'm litle confused by the const modifier, particularly when use const
Are string literals "real constants", whatever that means? I thought
you
were just supposed to pretend that they were constants, and treat them
as such, to prevent the wrath of UB.

Here, C's subtle goals for portability surface. Some memory pages are
marked read-only. Any attempted write to a read-only page by a user
mode program [contrasted with supervisor mode running the OS's kernel]
will result in an interrupt raised by the Memory Management Unit
[MMU], the part of the CPU that translates virtual addresses to
physical addresses. This interrupt notifies the kernel your program is
behaving badly. The default behavior in this case is an abrupt
termination known as a "core dump."

Executable files produced by modern linkers are partitioned into
segments. The ".data" segment is expected to be read-only and *may* be
mapped to a read-only page in virtual memory. Attempting to write it
results in the above behavior. This is the meaning of "real constant":
the hardware and OS will not permit you to write it after the loader
brings that segment into memory and protects the page. String literals
are typically placed in the ".data" segment, so treat them as "real
constants."
The above is all system-specific, and has nothing *directly* to do
with C. It's *indirectly* related to C in that (a) it's probably true
of many C implementations, and (b) it probably provided some of the
motivation for what the C standard actually does (and doesn't)
require.
This differs somewhat from use of the 'const' keyword. When const is
used in a variable definition, the compiler typically attempts to
infer its value. If the compiler can guess the initial value at
compile time, and by definition the variable's value cannot change
after initialization, then it may optimize the value away. That is,
replace all instructions loading that variable with load-immediate
instructions. If you attempt to take the address of that variable, or
the compiler chooses not to get rid of it, it may place that value in
the ".data" segment again resulting in a "real constant."
"const" really means "read-only". An attempt to modify an object that
was declared as "const" invokes undefined behavior. As you say, the
compiler is free to use this information to guide optimization.
You may implicitly cast a non-const to const.
You cannot "implicitly cast" anything to antyhing. The term "cast"
refers only to the explicit operator.

A value may be implicitly *converted* to a const type.

[...]
Given a constant variable, you may cast away the const property and
then write to it. This is only guaranteed to work if you are certain
that the variable was defined as nonconst.
It's important to keep in mind that "const" and "constant" are two
different things. "const", in C, just means read-only. A "constant"
is what some languages refer to as a literal, such as 42, 'x', or 1.2.
(And a "constant expression" is one that an implementation is required
to be able to evaluate at compilation time.)

[snip]

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #10

P: n/a
* * const int *const*const***const**p;
Yeah... I'm not sure if someone wants to use a pointer like that
one...

My point wasn't how to declare, but when to declare.

So, I've come to one simple conclusion:
One should use const when the content won't be modified anywhere after
initialization, and if it will be (and I say that because in "const
char*" case my compiler doesn't warn about changin' it), just don't
use "const".
Sure there can be ways to chage it's data, but those are compiler
dependent and doesn't matter for what const means, right?
Jun 27 '08 #11

P: n/a
On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrote:
Malcolm McLean wrote:
So it is not exactly wrong to avoid const. Personally I try to keep it
to a minimum.

I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
Is that true? Wouldn't it be better to just learn what 'const' or
'restrict' or X does?
Jun 27 '08 #12

P: n/a
vi******@gmail.com wrote:
On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrote:
>Malcolm McLean wrote:
>>So it is not exactly wrong to avoid const. Personally I try to keep it
to a minimum.
I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
Is that true? Wouldn't it be better to just learn what 'const' or
'restrict' or X does?
It would be better, yes. Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently. Until
then, I'll just avoid it for fear of using it improperly
out of ignorance.

I'm suggesting that McLean's avoidance of `const' may be
motivated by feelings similar to mine about `restrict': don't
mess around with what you don't understand.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #13

P: n/a
Eric Sosman <es*****@ieee-dot-org.invalidwrites:
vi******@gmail.com wrote:
>On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrote:
>>Malcolm McLean wrote:
So it is not exactly wrong to avoid const. Personally I try to keep it
to a minimum.
I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
Is that true? Wouldn't it be better to just learn what 'const' or
'restrict' or X does?

It would be better, yes. Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently. Until
then, I'll just avoid it for fear of using it improperly
out of ignorance.

I'm suggesting that McLean's avoidance of `const' may be
motivated by feelings similar to mine about `restrict': don't
mess around with what you don't understand.
So why dont you bother to actually understand what they do mean?
Jun 27 '08 #14

P: n/a
Richard wrote:
Eric Sosman <es*****@ieee-dot-org.invalidwrites:
>vi******@gmail.com wrote:
>>On Jun 3, 1:32 am, Eric Sosman <esos...@ieee-dot-org.invalidwrote:
Malcolm McLean wrote:
So it is not exactly wrong to avoid const. Personally I try to keep it
to a minimum.
I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
Is that true? Wouldn't it be better to just learn what 'const' or
'restrict' or X does?
It would be better, yes. Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently. Until
then, I'll just avoid it for fear of using it improperly
out of ignorance.

I'm suggesting that McLean's avoidance of `const' may be
motivated by feelings similar to mine about `restrict': don't
mess around with what you don't understand.

So why dont you bother to actually understand what they do mean?
Low priority. First, my limited understanding of
`restrict' is that it's mostly an optimizer-enabling hint
to the compiler, not something whose addition affects the
operation or correctness (or incorrectness) of a program.
In this way it's similar to `register', another construct
I avoid (but for different reasons). Second, `restrict'
doesn't work at all with C89/C90/C95 compilers, and C99
compilers (although commoner than they used to be) are
still not exactly thick upon the ground.

So, when I tackle two-and-a-half pages of Standardese
beginning "Let D be a declaration of an ordinary identifier
that provides a means of designating an object P as a restrict-
qualified pointer to type T," I am not strongly motivated to
see the matter through to a conclusion.

That's why I "dont" [sic] bother. Not yet, at least.

As for `const', I believe my understanding is adequate.
On the basis of his posting, I'm suggesting that McLean's may
not be.

--
Er*********@sun.com
Jun 27 '08 #15

P: n/a
Leonardo Korndorfer wrote:
>
>const int *const*const***const**p;

Yeah... I'm not sure if someone wants to use a pointer like that
one...

My point wasn't how to declare, but when to declare.

So, I've come to one simple conclusion:
One should use const when the content won't be modified anywhere after
initialization, and if it will be (and I say that because in "const
char*" case my compiler doesn't warn about changin' it),
It won't warn about a write to the pointer object itself, but it should
warn when you write to what the pointer is pointing to.
just don't use "const".
Sure there can be ways to chage it's data, but those are compiler
dependent and doesn't matter for what const means, right?
Yes. If you do write to a const qualified object the further behaviour
of your program is undefined, which in practise means that it depends
on how exactly your compiler treated that object and other issues. If
there exists any chance at all that you might want a read-write object
then don't use the const qualifier.

Jun 27 '08 #16

P: n/a
Richard wrote:
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
>>>Eric Sosman <es*****@ieee-dot-org.invalidwrites:
>>> It would be better, yes. Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently. Until
then, I'll just avoid it for fear of using it improperly
out of ignorance.
>>>So why dont you bother to actually understand what they do mean?

How should I prioritize this against the many many other tasks
that I have to do? Would you say that this is more important

Is this some kind of joke? You managed to learn how to use pointers and
you have time to post here. One would have thought using features like
this would be a must for a C programmer who wants to best utilise the language.
One would; many don't.

--
"The original and modest plans had to be continually extended."/Sector General/

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

Jun 27 '08 #17

P: n/a
In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
>ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
>>>Eric Sosman <es*****@ieee-dot-org.invalidwrites:
>>>Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently.
>>>So why dont you bother to actually understand what they do mean?
>How should I prioritize this against the many many other tasks
that I have to do? Would you say that this is more important
>Is this some kind of joke?
Well, it was a minor joke in that I don't actually have a dog to feed,
but I do have other kinds of dependants that need to be fed regularly.
>You managed to learn how to use pointers and
you have time to post here. One would have thought using features like
this would be a must for a C programmer who wants to best utilise the language.
Well, the time I have spent investigating them so-far has suggested
that const and restrict are of minor value, and no match for the
Intra-Procedural Analysis (IPA) optimizer of the compilers I use.
So either they really are of little importance (or even of hinderance)
to "a C programmer who wants to best utilize the language" -- or
else they -are- of importance in some manner that I have not yet
discerned, in which case it will take a fair bit of effort to
get past my current perceptions that they are more or less useless.

Seeing as you implicitly claim to understand their uses and how
best to utilize them, then you can guide me as to their relative
importance compared to other things in my life. Would my "proper"
understanding of these features revolutionize my C programs? To the
point where I ought to be telling my boss, "I should put these other
tasks aside until I have sussed these features out, as I am assured
that they are the keys to the hidden temple of C and once I understand
them, I'll be five times as productive and able to cure yaws!" ?
Or is this more along the lines of "Probably it'd be a good idea
to attend to those dandelions on your front yard first... and to
wash the windows... and to change the oil in the car..." ??
--
"It's a hard life sometimes and the biggest temptation is to let
how hard it is be an excuse to weaken." -- Walter Dean Myers
Jun 27 '08 #18

P: n/a
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
>>ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>>In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
Eric Sosman <es*****@ieee-dot-org.invalidwrites:
>>>>Probably someday I'll set to
work to try to remedy my understanding of `restrict', and
maybe then I'll find ways to use it intelligently.
>>>>So why dont you bother to actually understand what they do mean?
>>How should I prioritize this against the many many other tasks
that I have to do? Would you say that this is more important
>>Is this some kind of joke?
Well, it was a minor joke in that I don't actually have a dog to feed,
but I do have other kinds of dependants that need to be fed regularly.
>>You managed to learn how to use pointers and
you have time to post here. One would have thought using features like
this would be a must for a C programmer who wants to best utilise the language.

Well, the time I have spent investigating them so-far has suggested
that const and restrict are of minor value, and no match for the
Intra-Procedural Analysis (IPA) optimizer of the compilers I use.
The compilers you use are of no interest to this group since, as you
constantly remind people, it is about standards compliant C. Especially
with regards to const, I find it hard to believe that you can not find
the time to make your code sturdier and more readable.
Jun 27 '08 #19

P: n/a
In article <g2**********@registered.motzarella.org>,
Richard <rg****@gmail.comwrote:
>ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>Well, the time I have spent investigating them so-far has suggested
that const and restrict are of minor value, and no match for the
Intra-Procedural Analysis (IPA) optimizer of the compilers I use.
>The compilers you use are of no interest to this group since, as you
constantly remind people, it is about standards compliant C.
Since const values are not really constants, and since restrict
as a model can't actually restrict anything to a meaningful degree,
both qualifiers exist only to express interface intent and to
give hints to the compiler about possible optimizations. How useful
is it to the compiler to have those optimization hints? Does it
make a difference, or are the qualifiers instant veriform appendexes,
of little more use in non-embedded programming than 'register' is ?
>Especially
with regards to const, I find it hard to believe that you can not find
the time to make your code sturdier and more readable.
One wonders what you would say to Dennis Ritchie about his
reticience to take up const and restrict?

http://www.lysator.liu.se/c/dmr-on-noalias.html

From: dm*@alice.UUCP
Newsgroups: comp.lang.c
Subject: noalias comments to X3J11
Message-ID: <77**@alice.UUCP>
Date: 20 Mar 88 08:37:58 GMT
[...]
Let me begin by saying that I'm not convinced that even the
pre-December qualifiers (`const' and `volatile') carry their
weight; I suspect that what they add to the cost of learning and
using the language is not repaid in greater expressiveness.

`Volatile', in particular, is a frill for esoteric applications,
and much better expressed by other means. Its chief virtue is
that nearly everyone can forget about it. `Const' is
simultaneously more useful and more obtrusive; you can't avoid
learning about it, because of its presence in the library
interface. Nevertheless, I don't argue for the extirpation of
qualifiers, if only because it is too late.

The fundamental problem is that it is not possible to write real
programs using the X3J11 definition of C. The committee has
created an unreal language that no one can or will actually use.
While the problems of `const' may owe to careless drafting of the
specification, `noalias' is an altogether mistaken notion, and
must not survive.
[...]
--
"There are some ideas so wrong that only a very intelligent person
could believe in them." -- George Orwell
Jun 27 '08 #20

P: n/a
In article <sl*******************@nospam.invalid>,
Antoninus Twink <no****@nospam.invalidwrote:
>On 3 Jun 2008 at 14:03, Walter Roberson wrote:
>I find it pretty amazing that you and Sossman, who are appalled if
people don't keep at the front of their mind that "long unsigned int
long" is a synonym for "unsigned long long", or fail to account for the
behavior of their code on a machine with no stack where fopen always
returns NULL, and generally seem content to waste hours of your time
pouring over the pointless minutiae of the dustier corners of the ANSI
Bible, should be so reluctant to figure out what const means.
I've read the Standard about what it means, but since after reading
the Standard, it -appears- to me to be mostly a waste of time,
I can't seem to bring myself to Drink The Cool-Aid quite yet.

Perhaps I should phrase the matter a different way:

Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
--
"They called it golf because all the other four letter words
were taken." -- Walter Hagen
Jun 27 '08 #21

P: n/a

"Eric Sosman" <es*****@ieee-dot-org.invalidwrote in message
Malcolm McLean wrote:
>>
"Leonardo Korndorfer" <le***********@gmail.comwrote in message
>>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?
Use const when you don't modify the string (or other thing pointed to)
within the function. constness only applies within the function's scope.
Outside the variables can be modified, and in fact usually are modified.
Only rarely is data provided in read-only arrays typed into the program
directly.

If this means something, I think it must mean something wrong.
A const-qualified object is const-qualified, period, whether it is
in or out of scope. An attempt to modify a const-qualified object
by name or via a const-qualified pointer requires the compiler to
issue a diagnostic; an attempt to modify it by other means yields
undefined behavior. Scope has naught to do with it.
void bar(char *str)
{
str[0] = 'f'';
/* here "Fred is not const */
printf("%s\n", str);
}
void foo(const char *str)
{
/* here "Fred" is const */
printf("%s\n", str);
/* illegal */
bar(str);
}
int main(void)
{
char astring[] = "Fred";
foo(astring);
/* legal */
bar(astring);
}

foo's constness of the parameter affects the string in foo's scope, but
doesn't propagate up.
>There's a bit of debate about the virtues of const. One problem is const
poisoning. Once a pointer becomes const, everything it touches has to be
const.

Perhaps you should explain what you mean by "touches." If
you mean "points at," the claim is wrong: It is entirely all
right for a pointer-to-const-Thing to point at a Thing that is
not const-qualified.
>Another problem is that constness applies only to the object directly
pointed to. However frequently structures contain other pointers, and you
want to const them as well.

What do you mean by "to const?" Is it anything like
"to int" or "to static?"
"to const" = "to apply the const qualifier to".
>So it is not exactly wrong to avoid const. Personally I try to keep it to
a minimum.

I almost never use `restrict', because my grasp of precisely
what it means appears to equal your grasp of `const'. We both
steer clear of what we don't comprehend.
>However if I am writing code to publish on my website const will usually
be included for a constant pointer parameter that the user provides. If
the pointer parameter is returned by another function in the same file,
however, I usually won't declare it const.

This may be an accurate description of your habits, but I
can't see any reason for using or not using `const' based on
which translation unit a function inhabits.
Consider this

/* load a Brookhaven PDB file */
PDB * loadpdb(char *fname);
/* get rid of it */
void killpdb(PDB *pdb);

/* get the amino acid sequence of the protein chain */
char *pdb_getsequence( const ? * pdb, int chain)

should the parameter be const? On any understanding of what the code is
doing, reading the sequence isn't going to modify the object.
However my answer is no. PDB is an opaque type. So it's none of caller's
business whether internally we mess about with the structure or not, for
instance to cache sequences.

On the other hand if a structure is intended to be filled out by the caller,
it makes sense to const it, to give him an assurance that the contents will
not have changed.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #22

P: n/a
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <sl*******************@nospam.invalid>,
Antoninus Twink <no****@nospam.invalidwrote:
>>On 3 Jun 2008 at 14:03, Walter Roberson wrote:
>>I find it pretty amazing that you and Sossman, who are appalled if
people don't keep at the front of their mind that "long unsigned int
long" is a synonym for "unsigned long long", or fail to account for the
behavior of their code on a machine with no stack where fopen always
returns NULL, and generally seem content to waste hours of your time
pouring over the pointless minutiae of the dustier corners of the ANSI
Bible, should be so reluctant to figure out what const means.

I've read the Standard about what it means, but since after reading
the Standard, it -appears- to me to be mostly a waste of time,
I can't seem to bring myself to Drink The Cool-Aid quite yet.

Perhaps I should phrase the matter a different way:

Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
I believe the answer to that is "no" (ignoring arbitrary changes in
unspecified behavior).

However, there are plenty of *incorrect* programs that are likely to
compile with no diagnostics, in which judicious use of "const" can get
the compiler to detect the error. For example:

/* const */ char *s = "hello";
s[0] = 'H';

On the other hand, adding "const" here means that you can't pass s as
an argument to a function that expects a (non-const) char*. On the
other other hand, if you're going to be passing s to such a function,
the parameter probably should have been declared "const" anyway. (See
"const poisoning".)

(If I were designing a new language from scratch, I'd probably make
const (or equivalent) the default for declared variables. Given
sufficiently flexible initialization, I suspect, with no real
evidence, that a lot of objects aren't actually modified after their
initialization. If you want to be able to modify an object later on,
declare it with a "var" keyword or some other special syntax.
Declaring an object with neither "var" nor an initializer would be an
error. Possibly nobody but me would want to use such a language.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #23

P: n/a
Walter Roberson wrote, On 03/06/08 19:03:

<snip>
Perhaps I should phrase the matter a different way:

Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
No. However there are programs with required diagnostics where the
required diagnostic will go away if you get rid of the const leaving you
with undiagnosed undefined behaviour.

markg@brenda:~$ cat t.c
int main(void)
{
/*const*/ char *fred="blogs";
*fred = 'B';
return 0;
}
markg@brenda:~$ gcc -ansi -pedantic -Wall -Wextra t.c
markg@brenda:~$ ./a.out
Segmentation fault
markg@brenda:~$

Uncomment the const and the program will not compile under gcc and under
*any* conforming compiler you will get some form of diagnostic.
--
Flash Gordon
Jun 27 '08 #24

P: n/a
Malcolm McLean wrote:
>
"Eric Sosman" <es*****@ieee-dot-org.invalidwrote in message
>>>
Use const when you don't modify the string (or other thing pointed
to) within the function. constness only applies within the function's
scope. Outside the variables can be modified, and in fact usually are
modified. Only rarely is data provided in read-only arrays typed into
the program directly.

If this means something, I think it must mean something wrong.
A const-qualified object is const-qualified, period, whether it is
in or out of scope. An attempt to modify a const-qualified object
by name or via a const-qualified pointer requires the compiler to
issue a diagnostic; an attempt to modify it by other means yields
undefined behavior. Scope has naught to do with it.
void bar(char *str)
{
str[0] = 'f'';
/* here "Fred is not const */
printf("%s\n", str);
}
void foo(const char *str)
{
/* here "Fred" is const */
printf("%s\n", str);
/* illegal */
bar(str);
}
int main(void)
{
char astring[] = "Fred";
foo(astring);
/* legal */
bar(astring);
}

foo's constness of the parameter affects the string in foo's scope, but
doesn't propagate up.
No, the string is non-const throughout the exeuction of
the program, and nothing changes that. The string is an
object and has no scope; only identifiers have scope. The
string in question is referred to by different identifiers
in different scopes: astring in main(), str in foo(), and
str in bar(). (The two identifiers spelled `str' are distinct
identifiers with distinct scopes, and are in no way connected.)
The fact that different references have different properties
is not surprising -- think of pointing at the string's first
character with a `char*' or with a `void*', for example.
>>Another problem is that constness applies only to the object directly
pointed to. However frequently structures contain other pointers, and
you want to const them as well.

What do you mean by "to const?" Is it anything like
"to int" or "to static?"
"to const" = "to apply the const qualifier to".
So if I understand your complaint correctly, you're
thinking of

struct st {
char *data;
struct st *next;
};

void foo(const struct st *p) { ... }

is limited to saying "foo will not change *p," but you'd like
to be able to say "foo will not change *p and will not change
*p->data, but might change *p->next->data." Well, all right:
C's syntax is not expressive enough to describe foo's intentions
to that degree of detail.

But your solution to C's inability to say everything is
to refuse to say anything at all? That strikes me as odd:
You're throwing away what you're able to get simply because
you can't get all you could imagine. You'd like to be able to
say "violet" and "mauve" and "lilac" and "indigo," and your
response to C's offer of a generic "purple" is to refuse to
say anything at all?
>>However if I am writing code to publish on my website const will
usually be included for a constant pointer parameter that the user
provides. If the pointer parameter is returned by another function in
the same file, however, I usually won't declare it const.

This may be an accurate description of your habits, but I
can't see any reason for using or not using `const' based on
which translation unit a function inhabits.
Consider this

/* load a Brookhaven PDB file */
PDB * loadpdb(char *fname);
/* get rid of it */
void killpdb(PDB *pdb);

/* get the amino acid sequence of the protein chain */
char *pdb_getsequence( const ? * pdb, int chain)

should the parameter be const? On any understanding of what the code is
doing, reading the sequence isn't going to modify the object.
However my answer is no. PDB is an opaque type. So it's none of caller's
business whether internally we mess about with the structure or not, for
instance to cache sequences.

On the other hand if a structure is intended to be filled out by the
caller, it makes sense to const it, to give him an assurance that the
contents will not have changed.
I still don't get the connection between these questions,
which are legitimate design questions, and which translation
unit(s) the functions reside in.

--
Er*********@sun.com

Jun 27 '08 #25

P: n/a
On Jun 3, 1:53*pm, Leonardo Korndorfer <leokorndor...@gmail.com>
wrote:
So, I've come to one simple conclusion:
One should use const when the content won't be modified anywhere after
initialization, and if it will be (and I say that because in "const
char*" case my compiler doesn't warn about changin' it), just don't
use "const".

Const is the default for me. If something's non-const then it's an
exception. In fact, you could mimick my way of programming simply by
doing the following:

1: Make everything const
2: Try to compile
3: If you get compile errors, remove the offending const's
Jun 27 '08 #26

P: n/a
Walter Roberson wrote:
>
.... snip ...
>
Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
As long as you specified ignoring the timing, I believe the answer
is no. However the 'const' has the great advantage of catching
various user errors, and improving the code optimization.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #27

P: n/a
On Tue, 03 Jun 2008 18:03:27 +0000, Walter Roberson wrote:
Is there any conforming program that uses 'const' which have a different
output (aside from timing) if all of the 'const' were removed from the
program?
#include <assert.h>
int main(void) {
assert((const char) 0 == 1);
}

:-)
Jun 27 '08 #28

P: n/a
On Tue, 03 Jun 2008 22:28:04 +0000, Walter Roberson wrote:
If a program uses const, does that give the compiler any liberties for
optimization that would not be present in the const-less version of
the same program? [...]
I'm thinking vaguely of things like constant folding [...]
Sure, and as a result, the value of &(const int){0} == &(const int){0} is
unspecified, but that of &(int){0} == &(int){0} is guaranteed to be 0.
Jun 27 '08 #29

P: n/a
In article <a7**************************@cache3.tilbu1.nb.hom e.nl>,
Harald van =?UTF-8?b?RMSzaw==?= <tr*****@gmail.comwrote:
>On Tue, 03 Jun 2008 18:03:27 +0000, Walter Roberson wrote:
>Is there any conforming program that uses 'const' which have a different
output (aside from timing) if all of the 'const' were removed from the
program?
>#include <assert.h>
int main(void) {
assert((const char) 0 == 1);
}
I gather you are pointing out that the assertion failed message will
contain the string 'const' in one case, but not in the 'other' ?
True, that would be different output. And presumably the same sort
of technique could be used in other stringifications -- e.g.,
the string length of a stringified argument containing const would
be different than if the const were present.

Tricky ;-)
--
"There is nothing so bad but it can masquerade as moral."
-- Walter Lippmann
Jun 27 '08 #30

P: n/a

"Eric Sosman" <Er*********@sun.comwrote in message
Malcolm McLean wrote:
>>
"Eric Sosman" <es*****@ieee-dot-org.invalidwrote in message
>> If this means something, I think it must mean something wrong.
A const-qualified object is const-qualified, period, whether it is
in or out of scope. An attempt to modify a const-qualified object
by name or via a const-qualified pointer requires the compiler to
issue a diagnostic; an attempt to modify it by other means yields
undefined behavior. Scope has naught to do with it.

No, the string is non-const throughout the exeuction of
the program, and nothing changes that. The string is an
object and has no scope; only identifiers have scope. The
string in question is referred to by different identifiers
in different scopes: astring in main(), str in foo(), and
str in bar(). (The two identifiers spelled `str' are distinct
identifiers with distinct scopes, and are in no way connected.)
The fact that different references have different properties
is not surprising -- think of pointing at the string's first
character with a `char*' or with a `void*', for example.
You're making it sound terribly complicated. A defintion is often an enemy
to an explanation.
>"to const" = "to apply the const qualifier to".

So if I understand your complaint correctly, you're
thinking of

struct st {
char *data;
struct st *next;
};

void foo(const struct st *p) { ... }

is limited to saying "foo will not change *p," but you'd like
to be able to say "foo will not change *p and will not change
*p->data, but might change *p->next->data." Well, all right:
C's syntax is not expressive enough to describe foo's intentions
to that degree of detail.

But your solution to C's inability to say everything is
to refuse to say anything at all? That strikes me as odd:
You're throwing away what you're able to get simply because
you can't get all you could imagine. You'd like to be able to
say "violet" and "mauve" and "lilac" and "indigo," and your
response to C's offer of a generic "purple" is to refuse to
say anything at all?
Yes. It's a bit like saying that Deep Indigo will be playing at the rock
concert. Better just to say "a famous rock band".
>
I still don't get the connection between these questions,
which are legitimate design questions, and which translation
unit(s) the functions reside in.
The translation unit, or source file, is a psychological factor.
Psychological factors are the most important consideration in the vast
majority of programming tasks.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #31

P: n/a
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
[...]
If a program uses const, does that give the compiler any liberties
for optimization that would not be present in the const-less
version of the same program?
[...]

I believe the answer, to a first approximation, is theoretically no,
but practically yes (assuming both versions are correct).

For example consider this:

void foo(void)
{
/* const */ int x = 42;
/* a whole bunch of code */
printf("x = %d\n", x);
}

With the "const", the compiler is free to assume that x is equal to
42, and to replace the printf call with puts("x = 42"). Without the
"const", the compiler can't necessarily be sure that the "whole bunch
of code" doesn't modify the value of x, so it potentially needs to
generate code to re-load its value and pass it to printf. But if, as
we assumed, the program is correct with or without const, then the
"whole bunch of code" in fact *doesn't* modify x, and in principle the
compiler should be able to figure this out (in cases that aren't
isomorphic to the halting problem).

"const" is a way of telling the compiler something that you, the
programmer, already know, and that the compiler might or might not
have been able to figure out for itself.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #32

P: n/a
santosh wrote:
>
Doubtless Eric has numerous other work-related responsibilities. He has
previously indicated that he has practised professional C programming
from the late 70s.
Yes, but do not infer continuity. I first used C in
about 1978-9, then didn't use it at all for about five years,
then used it intensively for about fifteen, and have used it
less and less over the last ten.
I doubt he's still actively involved in professional
C programming.
Of late, it's mostly Java. Oddly enough, though, this
very week I have started on some changes to a large C program
whose roots go 'way back to the earlier pre-Standard days, and
am being reminded of just how much easier the Standard has made
the practice of C. This old-style stuff I'm struggling with
at the moment -- well, suffice it to say that five percent of
the source lines begin with # ...
Even if so, I don't think restrict is used all that
frequently in C code. I have hardly ever seen it in code that I have
dealt with. It probably isn't a priority matter for Eric.
Exactly. And as I've mentioned elsethread, the C99 compilers
that recognize `restrict' are not yet so abundant as to raise
fears that they might impair the ozone layer.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #33

P: n/a
Walter Roberson wrote:
CBFalconer <cb********@maineline.netwrote:
>Walter Roberson wrote:
>>Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
>As long as you specified ignoring the timing, I believe the answer
is no. However the 'const' has the great advantage of catching
various user errors, and improving the code optimization.

In reading your response, I thought of a possibility:

If a program uses const, does that give the compiler any liberties
for optimization that would not be present in the const-less
version of the same program? If Yes, then we directly have different
semantics for the two programs. ...
It only takes one example to establish the possibility:

const int foo;
...
int bar(...) {...; return n}

int foobar{...) {
...
while (...) {
bar(2 * foo);
}
return x;
}

and the expression 2 * foo can be moved outside the loop, because
foo is const. Thus it is known that bar, and any other functions
called, cannot modify it.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

** Posted from http://www.teranews.com **
Jun 27 '08 #34

P: n/a
Walter Roberson wrote:
Is there any conforming program that uses 'const' which have a
different output (aside from timing) if all of the 'const' were
removed from the program?
In C89, some conforming programs
can be rendered non conforming, by removal of const.

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
const zero = 0;

puts("X");
return zero;
}

/* END new.c */

--
pete
Jun 27 '08 #35

P: n/a
santosh wrote:
>
Even if so, I don't think restrict is used all that
frequently in C code. I have hardly ever seen it in code that I have
dealt with. It probably isn't a priority matter for Eric.
I assume from the above you don't work on a POSIX platform. POSIX APIs
make extensive use of restrict.

--
Ian Collins.
Jun 27 '08 #36

P: n/a
In article <6a*************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
>I assume from the above you don't work on a POSIX platform. POSIX APIs
make extensive use of restrict.
Not in POSIX.1-1990 they don't! And presumably not in any other
POSIX.* from before 1999.
--
Current spam load: 750-800 messages per day (March 4, 2008)
Jun 27 '08 #37

P: n/a
Walter Roberson wrote:
In article <6a*************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
>I assume from the above you don't work on a POSIX platform. POSIX APIs
make extensive use of restrict.

Not in POSIX.1-1990 they don't! And presumably not in any other
POSIX.* from before 1999.
A modern POSIX system will have the C99 standard library interface.

--
Ian Collins.
Jun 27 '08 #38

P: n/a
Ian Collins wrote:
santosh wrote:
>>
Even if so, I don't think restrict is used all that
frequently in C code. I have hardly ever seen it in code that I have
dealt with. It probably isn't a priority matter for Eric.
I assume from the above you don't work on a POSIX platform. POSIX
APIs make extensive use of restrict.
I was talking about applications that I have been involved with. They
were both Windows as well as POSIX based, but I don't really recall
seeing restrict used. I suspect that the situation is different for
system and library code. The code for most large systems go back way
before 1999, and unless performance sucks, I don't see how extensive
addition of restrict would be sanctioned.

The problem with restrict is that it is too easy to use it improperly.
Frankly speaking most of the C programmers I have worked with were not
even aware of restrict. Unlike misuse of const, there would likely be
no helpful diagnostic from the compiler, leading to subtly broken
programs.

Jun 27 '08 #39

P: n/a
Ian Collins wrote:
Walter Roberson wrote:
>In article <6a*************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
>>I assume from the above you don't work on a POSIX platform. POSIX APIs
make extensive use of restrict.
Not in POSIX.1-1990 they don't! And presumably not in any other
POSIX.* from before 1999.

A modern POSIX system will have the C99 standard library interface.
... and the caller can use the library without ever needing
to write `restrict'.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #40

This discussion thread is closed

Replies have been disabled for this discussion.