473,394 Members | 1,875 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,394 software developers and data experts.

Is const really const?

Hi all,

I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.

Thanks and regards
Rohit
Dec 17 '07 #1
29 1826
Rohit kumar Chandel wrote:
Hi all,

I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
If you didn't get at least three warnings for the above, turn your
compiler's warning level up so it tells you what is wrong with your code.

Yes C will let you get away with what you have written, but the result
is undefined behaviour.

--
Ian Collins.
Dec 17 '07 #2
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
In most of the English-speaking world outside India, "doubt" is not
merely a synomym for "question. In international forums like this
one, you'd have a better chance of being understood if you write "I
have a question about the const keyword".

In your program above, the declaration
int *pp = &p;
violates a constraint. For one compiler, it produces a warning
message:
warning: initialization discards qualifiers from pointer target type

You can't legally assign the address of a const object to a non-const
pointer object. This rule exists precisly to avoid the problem you're
seeing. Once the compiler diagnoses the problem, though, it's allowed
to continue to compile the program.

Increase the warning level of your compiler, and pay attention to any
warning messages it produces.

If you really want to modify a const object then ... well, first of
all, you shouldn't try to modify a const object; if you need to modify
it, it shouldn't have been declared const in the first place.

But here's a way to do what you're trying to do:

#include <stdio.h/* required for printf */
int main(void)
{
const int p = 5;
int *pp = (int*)&p; /* The cast suppresses the warning */
++(*pp);
printf("%d\n", p);
return 0;
}

The cast in effect tells the compiler that you know what you're doing.
This is almost always a bad idea, and the behavior of the program is
undefined. A compiler could *assume* that p is never modified (since
you promised not to modify it) and print 5 even if you've managed to
store the value 6 in its memory location.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 17 '07 #3
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
The line

int* pp = &p;

should have been diagnostized by the compiler.

Yours,

--
Jean-Marc
Dec 17 '07 #4

"Keith Thompson" <ks***@mib.orgwrote in message
news:87************@kvetch.smov.org...
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.

In most of the English-speaking world outside India, "doubt" is not
merely a synomym for "question. In international forums like this
one, you'd have a better chance of being understood if you write "I
have a question about the const keyword".

In your program above, the declaration
int *pp = &p;
violates a constraint. For one compiler, it produces a warning
message:
warning: initialization discards qualifiers from pointer target type

You can't legally assign the address of a const object to a non-const
pointer object. This rule exists precisly to avoid the problem you're
seeing. Once the compiler diagnoses the problem, though, it's allowed
to continue to compile the program.

Increase the warning level of your compiler, and pay attention to any
warning messages it produces.

If you really want to modify a const object then ... well, first of
all, you shouldn't try to modify a const object; if you need to modify
it, it shouldn't have been declared const in the first place.

But here's a way to do what you're trying to do:

#include <stdio.h/* required for printf */
int main(void)
{
const int p = 5;
int *pp = (int*)&p; /* The cast suppresses the warning */
++(*pp);
printf("%d\n", p);
return 0;
}

The cast in effect tells the compiler that you know what you're doing.
This is almost always a bad idea, and the behavior of the program is
undefined. A compiler could *assume* that p is never modified (since
you promised not to modify it) and print 5 even if you've managed to
store the value 6 in its memory location.
Thanks Mr Thompson for providing insight and at the same time correcting
english grammer as well :-)
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
Dec 17 '07 #5
Rohit kumar Chandel wrote:
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
You misunderstand. Modifying anything declared const results in
undefined behaviour.
--
Ian Collins.
Dec 17 '07 #6
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
[...]
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
I don't know where the "in the module in which it is defined" wording
comes from.

If an object is declared as "const", then there is no way to modify
that object without invoking undefined behavior.

I suppose you could define an object as "const" in one translation
unit, and declare it without the "const" in another translation unit,
and the implementation *might* not catch the error, but it's still an
error.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 17 '07 #7
On Dec 17, 2:49 pm, "Rohit kumar Chandel"
<rohitkumar.chan...@in.bosch.comwrote:
"Keith Thompson" <ks...@mib.orgwrote in message

news:87************@kvetch.smov.org...
"Rohit kumar Chandel" <rohitkumar.chan...@in.bosch.comwrites:
I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
In most of the English-speaking world outside India, "doubt" is not
merely a synomym for "question. In international forums like this
one, you'd have a better chance of being understood if you write "I
have a question about the const keyword".
In your program above, the declaration
int *pp = &p;
violates a constraint. For one compiler, it produces a warning
message:
warning: initialization discards qualifiers from pointer target type
You can't legally assign the address of a const object to a non-const
pointer object. This rule exists precisly to avoid the problem you're
seeing. Once the compiler diagnoses the problem, though, it's allowed
to continue to compile the program.
Increase the warning level of your compiler, and pay attention to any
warning messages it produces.
If you really want to modify a const object then ... well, first of
all, you shouldn't try to modify a const object; if you need to modify
it, it shouldn't have been declared const in the first place.
But here's a way to do what you're trying to do:
#include <stdio.h/* required for printf */
int main(void)
{
const int p = 5;
int *pp = (int*)&p; /* The cast suppresses the warning */
++(*pp);
printf("%d\n", p);
return 0;
}
The cast in effect tells the compiler that you know what you're doing.
This is almost always a bad idea, and the behavior of the program is
undefined. A compiler could *assume* that p is never modified (since
you promised not to modify it) and print 5 even if you've managed to
store the value 6 in its memory location.

Thanks Mr Thompson for providing insight and at the same time correcting
english grammer as well :-)
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
use #define :), i hope i am not dragging to wrong direction.
clarify it with example.- Hide quoted text -

- Show quoted text -
Dec 17 '07 #8
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
Thanks Mr Thompson for providing insight and at the same time correcting
english grammer as well :-)
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
An object which has been declared const may not be modified without
undefined behaviour. But you may get const view of non const objects. In
the later case, it is possible that you have two aliases, one const, one
not and then it is possible to modify the object. And I'm pretty sure but
I've not checked -- that you can even cast the const away of a const view
while staying in the defined realm.

void f1(int const* p1, int* p2) {
*p2 = 42;
}

void f2(int const* p1) {
*(int*)p1 = 36;
}

void foo() {
int const i1 = 1;
int i2 = 2;

f1(&i1, (int*)&i1); /* trigger undefined behaviour */
f2(&i1); /* trigger undefined behaviour */
f1(&i2, &i2); /* no undefined behaviour */
f2(&i2); /* probably no undefined behaviour */
}

--
Jean-Marc
Dec 17 '07 #9

"Keith Thompson" <ks***@mib.orgwrote in message
news:87************@kvetch.smov.org...
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
[...]
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these
materials
say that a variable declared to be const can not be modified in the
module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it
the
function, file or anything else.Does it mean that there is a normal way
to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.

I don't know where the "in the module in which it is defined" wording
comes from.

If an object is declared as "const", then there is no way to modify
that object without invoking undefined behavior.

I suppose you could define an object as "const" in one translation
unit, and declare it without the "const" in another translation unit,
and the implementation *might* not catch the error, but it's still an
error.

--
Here is the cause of my confusion. Thought it'll help you to understand the
problem better. This is from one of training slides. Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
....
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
....
void killRTC()
{
pRTC = NULL; /* <- ? */
}
....
??? Is the line in 'killRTC' allowed ???

Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
by this module (but maybe changed by another module).
Here next variable to the right is '*pRTC',
so '*pRTC' will not be changed by this module,
so the value of the memory where 'pRTC' points to will not be changed.
But the variable 'pRTC' is allowed to change!
So the code on the page before is correct and works.

Best Regards
Rohit
Dec 17 '07 #10
On Mon, 17 Dec 2007 17:47:49 +0530, "Rohit kumar Chandel"
<ro****************@in.bosch.comwrote:
>Here is the cause of my confusion. Thought it'll help you to understand the
problem better. This is from one of training slides. Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
...
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
...
void killRTC()
{
pRTC = NULL; /* <- ? */
}
...
??? Is the line in 'killRTC' allowed ???

Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
by this module (but maybe changed by another module).
Here next variable to the right is '*pRTC',
so '*pRTC' will not be changed by this module,
so the value of the memory where 'pRTC' points to will not be changed.
But the variable 'pRTC' is allowed to change!
So the code on the page before is correct and works.

Best Regards
Rohit
pRTC is a pointer to a constant, not a constant pointer. So pRTC may
be changed.

Jim
Dec 17 '07 #11
Rohit kumar Chandel wrote:
....
Here is the cause of my confusion. Thought it'll help you to understand the
problem better. This is from one of training slides. Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
...
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
...
void killRTC()
{
pRTC = NULL; /* <- ? */
}
...
??? Is the line in 'killRTC' allowed ???

Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
by this module (but maybe changed by another module).

That last line is simply and completely wrong. I'd recommend not
trusting anything you've learned from that training course. Someone who
made that mistake is likely to have made many other mistakes as well.
Dec 17 '07 #12
Rohit kumar Chandel wrote:
Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
That's different from what you think it means.

This:
volatile T_RTC *const pRTC = CLOCK_ADRESS;
means the keyword 'const' indicates that pRTC must not be changed.

This:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
means the keyword 'const' indicates that what pRTC points to,
must not be changed.

Take a look at the prototypes for copying functions in string.h

void *memcpy(void *s1, const void *s2, size_t n);
void *memmove(void *s1, const void *s2, size_t n);
char *strcpy(char *s1, const char *s2);
char *strncpy(char *s1, const char *s2, size_t n);
char *strcat(char *s1, const char *s2);
char *strncat(char *s1, const char *s2, size_t n);

You'll notice that the second parameter
always points to a const qualified type.
This indicates that the function will not
alter the value of anything that s2 points to.

The guarantee that the function will not
alter the value of anything that s2 points to,
is in the standard description of the library functions;
the presence of the const keyword in those prototypes,
is merely an indication that that is the case.

--
pete
Dec 17 '07 #13
Rohit kumar Chandel wrote:
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
Not in scope. (You can't modify what doesn't exist.)

Dec 17 '07 #14
"Rohit kumar Chandel" <ro****************@in.bosch.comwrites:
[...]
Here is the cause of my confusion. Thought it'll help you to understand the
problem better. This is from one of training slides. Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
...
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
...
void killRTC()
{
pRTC = NULL; /* <- ? */
}
...
??? Is the line in 'killRTC' allowed ???
Certainly; it's not even questionable. pRTC itself is not const. The
object that it *points to* is const (and volatile).

So this:

pRTC = NULL;

is perfectly ok, whereas this:

pRTC->std = 42; /* constraint violation! */

is not, because it attempts to modify a const object.

See if you can find a program called "cdecl". For example:

% cdecl
Type `help' or `?' for help
cdeclexplain const volatile int *obj
declare obj as pointer to const volatile int
cdecl>
Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
by this module (but maybe changed by another module).
The object that must not be changed (at least not directly) is *pRTC,
not pRTC itself.

Once again, "modules" have nothing to do with it. C doesn't even
define anything called a "module". (Perhaps it's meant to refer to a
translation unit, which roughly means a source file. It's true that,
in some cases, requirements are not enforced as strictly across
translation units as within them, but the requirements are still
there.)

Can you find out just what is meant by a "module"?
Here next variable to the right is '*pRTC',
so '*pRTC' will not be changed by this module,
so the value of the memory where 'pRTC' points to will not be changed.
But the variable 'pRTC' is allowed to change!
So the code on the page before is correct and works.
Right.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 17 '07 #15
Sheth Raxit <ra************@gmail.comwrites:
[...]
>I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
use #define :), i hope i am not dragging to wrong direction.
>clarify it with example.
"use #define"? How, exactly, would #define solve the problem?

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 17 '07 #16
If one variable defined const, you can't change variable's value via
this variable.
However it is exactly correct.

#include <stdio.h>

int main()
{
const int num = 12;
int * pNum;

// num = 12; wrong. you can't change a const variable's value.

pNum = &num;
*pNum = 13; // this is perfectly correct.
// num isn't 12 anymore

printf("%d", num);

}

#define SIZE 10;

means SIZE is 10 in everywhere.
Dec 17 '07 #17
Jean-Marc Bourguet <j...@bourguet.orgwrote:
An object which has been declared const
s/declared/defined/
may not be modified without undefined behaviour. But you may
get const view of non const objects. In the later case, it is
possible that you have two aliases, one const, one not and then
it is possible to modify the object. And I'm pretty sure but
I've not checked -- that you can even cast the const away of a
const view while staying in the defined realm.
You can, though it's generally ill advised.
void f1(int const* p1, int* p2) {
*p2 = 42;
}

void f2(int const* p1) {
*(int*)p1 = 36;
}

void foo() {
int const i1 = 1;
int i2 = 2;

f1(&i1, (int*)&i1); /* trigger undefined behaviour */
f2(&i1); /* trigger undefined behaviour */
f1(&i2, &i2); /* no undefined behaviour */
f2(&i2); /* probably no undefined behaviour */
}
The last line is okay since i2 is not const qualified; but again:
the action of f2() is ill advised.

--
Peter
Dec 17 '07 #18
Rohit kumar Chandel wrote:
Hi all,

I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
<snip>
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
"if you lie to the compiler, it will get its revenge".

const means the compiler will not let you overtly change the value. You
can still lie, cast away the constness, use a pointer to access it, and
so forth. The result is a broken programme. It may still compile, if
you've been devious enough. How many warnings did you get?
--
Mark McIntyre

CLC FAQ <http://c-faq.com/>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Dec 17 '07 #19
quasimodo <ali...@gmail.comwrote:

[Please quote the material relevant to your reply. Please also
read previous responses in the thread to avoid repeating
mistakes that have already been corrected.]
If one variable defined const, you can't change variable's
value via this variable.
However it is exactly correct.
By "it" do you mean what follows? If so, you're mistaken.
#include <stdio.h>

int main()
{
const int num = 12;
int * pNum;

// num = 12; wrong. you can't change a const variable's value.

pNum = &num;
This is the same error the OP had. It violates a constraint and
requires a diagnostic.
*pNum = 13; // this is perfectly correct.
// num isn't 12 anymore
Even applying a cast in the assignment of pNum above, the
subsequent behaviour of this line is not defined by the C
standard. So it's pointless saying what num will or won't
be.
>
printf("%d", num);
The last line of a text stream should be terminated with
a newline for maximally portable code.
}

#define SIZE 10;
means SIZE is 10 in everywhere.
No it means SIZE will expand to 10; (i.e. 10 followed by a semi-
colon).

I advise you to read the FAQ and fix some of your own misconceptions
before trying to educate others.

--
Peter
Dec 17 '07 #20

"Rohit kumar Chandel" <ro****************@in.bosch.comwrote in message
news:fk**********@news4.fe.internet.bosch.com...
Hi all,

I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
you may be using a compiler which is fully ANSI compliant. I get this
warning when I try to compile the same code:

C:\>gcc const1.c
const1.c: In function `main':
const1.c:4: warning: initialization discards qualifiers from pointer target
type.

This warning may as well be an error be setting some other options. Or in in
other compilers its may be error by default.

Is const really const ? Just run the program with the change of making p
into a global variable and you get this result:

C:\>a.exe
13 [main] a 3232 handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
10820 [main] a 3232 open_stackdumpfile: Dumping stack trace to
a.exe.stackdump

Now you can decide for yourself !

Regards,
Ravishankar



Dec 18 '07 #21
Peter Nilsson <ai***@acay.com.auwrites:
Jean-Marc Bourguet <j...@bourguet.orgwrote:
An object which has been declared const

s/declared/defined/
Oops
may not be modified without undefined behaviour. But you may
get const view of non const objects. In the later case, it is
possible that you have two aliases, one const, one not and then
it is possible to modify the object. And I'm pretty sure but
I've not checked -- that you can even cast the const away of a
const view while staying in the defined realm.

You can,
Thanks for confirming.
though it's generally ill advised.
Agreed.

--
Jean-Marc
Dec 18 '07 #22
Thanks Mr Thompson for providing insight and at the same time correcting
english grammer as well :-)
I have one more question on const keyword. I have gone through lot of
reading material to find its answer, but in vain. Most of these materials
say that a variable declared to be const can not be modified in the module
in which it is defined. From this I assume it can be modified by code
outside the module it is defined in. But what is a module here. Is it the
function, file or anything else.Does it mean that there is a normal way to
do it (apart from supressing warnings by using explicit cast). Please
clarify it with example.
A module means in C standard terms a "translation unit" -the result of
running the preprocessor over a C source file...

Dec 18 '07 #23
Here is the cause of my confusion. Thought it'll help you to understand
the
problem better. This is from one of training slides. Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
...
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
...
void killRTC()
{
pRTC = NULL; /* <- ? */
}
...
??? Is the line in 'killRTC' allowed ???

Explaination:
const volatile T_RTC *pRTC = CLOCK_ADRESS;
The keyword 'const' indicates that the variable must not be changed
by this module (but maybe changed by another module).
Here next variable to the right is '*pRTC',
so '*pRTC' will not be changed by this module,
so the value of the memory where 'pRTC' points to will not be changed.
But the variable 'pRTC' is allowed to change!
So the code on the page before is correct and works.
Explanation:

First understand that const means "read-only" (Read Dan Sak's article on
const : "Using "const" correctly !")

The global variable pRTC is pointer to an object that can only be read
through pRTC. pRTC by itself is normal pointer variable
which can be modified. Additionally the volatile says that the value of that
object can also change unpredictable, so no memory optimizations
may be performed by the compiler when **accessing that object through**
pRTC.

About pointer's and the type qualifiers (const and volatile)

const int i; // i is const
const int *cip; // cip points to a const int. cip is not const.
int *const cpi; // cpi is constant pointer (always points to the same
object). The object pointed to may be modified.
volatile int i; // i is volatile
volatile int *vip; // cip points to a volatile int. cip is not volatile
int *volatile vpi; // cpi is volatile pointer (can change unpredictably).
The object pointed to is a normal variable.




Dec 18 '07 #24

*pNum = 13; // this is perfectly correct.
Its correct only if you accept the outcome is undefined :)
// num isn't 12 anymore

printf("%d", num);

}

#define SIZE 10;

means SIZE is 10 in everywhere.
There is big difference between const variables and preprocesor
"constants"..

Dec 18 '07 #25
Rohit kumar Chandel wrote:
>
.... snip ...
>
Here is the cause of my confusion. Thought it'll help you to
understand the problem better. This is from one of training slides.
Goes like this:
/* real-time clock (hardware) */
const volatile T_RTC *pRTC = CLOCK_ADRESS;
...
void printTime()
{
printf("%d:%d:%d\n",
pRTC->std,pRTC->min,pRTC->sec);
}
...
void killRTC()
{
pRTC = NULL; /* <- ? */
}
...
??? Is the line in 'killRTC' allowed ???
Please indent your code, or possibly avoid using tabs.

The pRTC definition statement makes pRTC a pointer (non const) to a
(const) thing of type CLOCK_ADDRESS. You can modify the pointer
without modifying the thing pointed at.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
--
Posted via a free Usenet account from http://www.teranews.com

Dec 20 '07 #26
Rohit kumar Chandel wrote:
>
.... snip ...
I have one more question on const keyword. I have gone through lot
of reading material to find its answer, but in vain. Most of these
materials say that a variable declared to be const can not be
modified in the module in which it is defined. From this I assume
it can be modified by code outside the module it is defined in.
....

Don't assume. It simply should not be modified. That means it has
to be initialized in the definition statement, which in turn may be
a function call.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Dec 20 '07 #27
Rohit kumar Chandel wrote:
>
I have a doubt in const keyword. My understanding says that a
variable declared const can not be modified by the module it is
defined in. Then consider the following code segment:

main() {
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has
to be a constant. Please clarify my doubt.
If you turn up the warning level sufficiently the statement
int *pp = &p;
should trigger a complaint.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Dec 20 '07 #28

"Ravishankar S" <ra***********@in.bosch.comwrote in message
news:fk**********@news4.fe.internet.bosch.com...
>
"Rohit kumar Chandel" <ro****************@in.bosch.comwrote in message
news:fk**********@news4.fe.internet.bosch.com...
Hi all,

I have a doubt in const keyword. My understanding says that a variable
declared const can not be modified by the module it is defined in. Then
consider the following code segment:
main()
{
const int p =5;
int* pp = &p;
++(*pp);
printf("%d\n",p);
}
To my surprise it increments value of p by one where p has to be a
constant. Please clarify my doubt.
you may be using a compiler which is fully ANSI compliant. I get this
warning when I try to compile the same code:

C:\>gcc const1.c
const1.c: In function `main':
const1.c:4: warning: initialization discards qualifiers from pointer
target
type.

This warning may as well be an error be setting some other options. Or in
in
other compilers its may be error by default.

Is const really const ? Just run the program with the change of making p
into a global variable and you get this result:

C:\>a.exe
13 [main] a 3232 handle_exceptions: Exception:
STATUS_ACCESS_VIOLATION
10820 [main] a 3232 open_stackdumpfile: Dumping stack trace to
a.exe.stackdump

Now you can decide for yourself !

Regards,
Ravishankar
I too got the warning :
c:\msvc\bin\rkc2.c(7) : warning C4090: 'initializing' : different const or
volatile qualifiers
But even after making p global, i get the same warning.
But my misconception is gone now....
I would put the summary in these words :

const is a promise made by the programmer to the compiler that once
initialized he'll not
change the value of a const variable. Compiler tries its best to keep the
promise ,by not allowing programmer modify the const variable directly (p++
gives an error, straightaway).

Modifying const variable by indirect means (as done by me by defining a
pointer to it)
results in undefined behaviour and may vary from compiler to compiler . So
some compilers may give warnings and others may give error for it.

Thanks to All
Dec 20 '07 #29
Rohit kumar Chandel wrote:
....
I would put the summary in these words :

const is a promise made by the programmer to the compiler that once
initialized he'll not
change the value of a const variable. Compiler tries its best to keep the
promise ,by not allowing programmer modify the const variable directly (p++
gives an error, straightaway).

Modifying const variable by indirect means (as done by me by defining a
pointer to it)
results in undefined behaviour and may vary from compiler to compiler . So
some compilers may give warnings and others may give error for it.
I think your summary falls a little short, in that it misses a key
distinction. The easiest way to explain this is with code examples:
const int i=1;
int j = 2;

*&i = 3; // constraint violation
*(int*)&i = 4; // undefined behavior
*&j = 5; // defined behavior
*(const int *)&j = 6; // constraint violation

Do you understand why?
Dec 20 '07 #30

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

Similar topics

5
by: Bolin | last post by:
Hi all, A question about smart pointers of constant objects. The problem is to convert from Ptr<T> to Ptr<const T>. I have look up and seen some answers to this question, but I guess I am too...
2
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't...
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. ...
16
by: herbertF | last post by:
Hi guys, In a program (not my own) I encountered the declaration of a constant pointer to an array consisting of two other const pointers to arrays. Not quite sure why they do it so complicated,...
8
by: Laurijssen | last post by:
What are the advantages of using const as often as possible in C? Does it help to declare integer function arguments as const? How about pointers and automatic const integers? const int...
0
by: d3x0xr | last post by:
Heh, spelled out in black and white even :) Const is useles... do NOT follow the path of considering any data consatant, because in time, you will have references to it that C does not handle,...
26
by: karthikbalaguru | last post by:
Hi, While trying to understand the difference between the following 2 methods, i have some interesting queries. Method 1) char *s = "Hello"; and Method 2) char s = "Hello"; How does the...
23
by: Kira Yamato | last post by:
It is erroneous to think that const objects will have constant behaviors too. Consider the following snip of code: class Person { public: Person(); string get_name() const
4
by: abendstund | last post by:
Hi, I have the following code and trouble with ambiguity due to operator overloading.. The code is also at http://paste.nn-d.de/441 snip>>
26
by: Turin | last post by:
Dear all; As far as I understand the idea behind getter methods, it is used to make sure that private memers of a class is returned appropriately to the calling object. However, if all I am...
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.