473,698 Members | 1,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const variables

Hi guys,

Consider the following statements.

const int *ptr; /* ie the contents pointed to by ptr cannot be
changed */

My question is how/who prevents the contents from being modified ?
Is it the C compiler that would give compile time error while trying to
change the contents ? Or is it the implementation that would somehow
prevent the contents from being modified during run time ?

Now consider the following two statements:

const int *ptr; /* line #1 */
int *tmp = ptr; /* line #2 */
*tmp = 100; /* line #3 , Is this valid ? */

Can we change the contents of "tmp" as done is line #3. Will the C
compiler generate warning on line #3. Will this cause some exception
during run time ?

One more question:
const int *ptr = malloc(4 * sizeof(int));
free(ptr); /* gives warning */

While freeing the memory, the compiler generated warning. What is the
reason behind that ? Can't this memory be freed ?
thanks a lot for any help in advance ...

Dec 29 '06 #1
4 1669
ju**********@ya hoo.co.in wrote:
Hi guys,

Consider the following statements.

const int *ptr; /* ie the contents pointed to by ptr cannot be
changed */
Almost: The pointed-to int cannot be changed through ptr,
but could be changed by some other pathway:

int target = 0;
const int *ptr = ⌖
*ptr = 42; /* compile error */
target = 42; /* no problem */
My question is how/who prevents the contents from being modified ?
Is it the C compiler that would give compile time error while trying to
change the contents ? Or is it the implementation that would somehow
prevent the contents from being modified during run time ?
The former. Now, if the target itself is also const, any
attempt to change it produces undefined behavior. For example,
an implementation might place the target in read-only memory
and might cause a trap on any attempt to write to it. Or it
might simply ignore the attempt to write and proceed merrily
and silently on its way. Or the write might succeed, producing
mysteries later on. Or the attempt to write might make demons
fly out of your nose: in theory, at least, Anything Can Happen.
Now consider the following two statements:

const int *ptr; /* line #1 */
int *tmp = ptr; /* line #2 */
*tmp = 100; /* line #3 , Is this valid ? */

Can we change the contents of "tmp" as done is line #3. Will the C
compiler generate warning on line #3. Will this cause some exception
during run time ?
The compiler will object to line #2, because you cannot
"subtract" a qualifier silently. The compiler's objection can
be silenced with a cast:

int *tmp = (int*)ptr;

(Of course, the compiler is permitted to issue warnings for
anything at all, and may still issue a warning for this line.
It must accept the revised code, though, even though it can
reject the original.)

At run time, the behavior depends on what ptr and tmp point
at. If the target is const the behavior of line #3 is undefined,
but if it is non-const the assignment works normally.
One more question:
const int *ptr = malloc(4 * sizeof(int));
free(ptr); /* gives warning */

While freeing the memory, the compiler generated warning. What is the
reason behind that ? Can't this memory be freed ?
When you free() a block of memory, you make it available
for re-use by a subsequent malloc(). Even if free() itself
does not modify the memory block, it exposes the block to
being modified later on. Hence, free(ptr) violates the promise
not to use ptr to modify the memory it points at.

You can still free() the memory, but not by using ptr as
it stands. One way is

free ((void*)ptr);

Even though ptr is const-qualified, (void*)ptr is not. See
the change to line #2 in the earlier example.

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 29 '06 #2

Eric Sosman wrote:
ju**********@ya hoo.co.in wrote:
Hi guys,

Consider the following statements.

const int *ptr; /* ie the contents pointed to by ptr cannot be
changed */

Almost: The pointed-to int cannot be changed through ptr,
but could be changed by some other pathway:

int target = 0;
const int *ptr = ⌖
*ptr = 42; /* compile error */
target = 42; /* no problem */
My question is how/who prevents the contents from being modified ?
Is it the C compiler that would give compile time error while trying to
change the contents ? Or is it the implementation that would somehow
prevent the contents from being modified during run time ?

The former. Now, if the target itself is also const, any
attempt to change it produces undefined behavior. For example,
an implementation might place the target in read-only memory
and might cause a trap on any attempt to write to it. Or it
might simply ignore the attempt to write and proceed merrily
and silently on its way. Or the write might succeed, producing
mysteries later on. Or the attempt to write might make demons
fly out of your nose: in theory, at least, Anything Can Happen.
Now consider the following two statements:

const int *ptr; /* line #1 */
int *tmp = ptr; /* line #2 */
*tmp = 100; /* line #3 , Is this valid ? */

Can we change the contents of "tmp" as done is line #3. Will the C
compiler generate warning on line #3. Will this cause some exception
during run time ?

The compiler will object to line #2, because you cannot
"subtract" a qualifier silently. The compiler's objection can
be silenced with a cast:

int *tmp = (int*)ptr;

(Of course, the compiler is permitted to issue warnings for
anything at all, and may still issue a warning for this line.
It must accept the revised code, though, even though it can
reject the original.)

At run time, the behavior depends on what ptr and tmp point
at. If the target is const the behavior of line #3 is undefined,
but if it is non-const the assignment works normally.
One more question:
const int *ptr = malloc(4 * sizeof(int));
free(ptr); /* gives warning */

While freeing the memory, the compiler generated warning. What is the
reason behind that ? Can't this memory be freed ?

When you free() a block of memory, you make it available
for re-use by a subsequent malloc(). Even if free() itself
does not modify the memory block, it exposes the block to
being modified later on. Hence, free(ptr) violates the promise
not to use ptr to modify the memory it points at.

You can still free() the memory, but not by using ptr as
it stands. One way is

free ((void*)ptr);

Even though ptr is const-qualified, (void*)ptr is not. See
the change to line #2 in the earlier example.
Thank you Eric for the nice explanation.

Dec 30 '06 #3

Eric Sosman wrote:
ju**********@ya hoo.co.in wrote:
Hi guys,

Consider the following statements.

const int *ptr; /* ie the contents pointed to by ptr cannot be
changed */

Almost: The pointed-to int cannot be changed through ptr,
but could be changed by some other pathway:

int target = 0;
const int *ptr = ⌖
*ptr = 42; /* compile error */
target = 42; /* no problem */
My question is how/who prevents the contents from being modified ?
Is it the C compiler that would give compile time error while trying to
change the contents ? Or is it the implementation that would somehow
prevent the contents from being modified during run time ?

The former. Now, if the target itself is also const, any
attempt to change it produces undefined behavior. For example,
an implementation might place the target in read-only memory
and might cause a trap on any attempt to write to it. Or it
might simply ignore the attempt to write and proceed merrily
and silently on its way. Or the write might succeed, producing
mysteries later on. Or the attempt to write might make demons
fly out of your nose: in theory, at least, Anything Can Happen.
Now consider the following two statements:

const int *ptr; /* line #1 */
int *tmp = ptr; /* line #2 */
*tmp = 100; /* line #3 , Is this valid ? */

Can we change the contents of "tmp" as done is line #3. Will the C
compiler generate warning on line #3. Will this cause some exception
during run time ?

The compiler will object to line #2, because you cannot
"subtract" a qualifier silently. The compiler's objection can
be silenced with a cast:

int *tmp = (int*)ptr;

(Of course, the compiler is permitted to issue warnings for
anything at all, and may still issue a warning for this line.
It must accept the revised code, though, even though it can
reject the original.)

At run time, the behavior depends on what ptr and tmp point
at. If the target is const the behavior of line #3 is undefined,
but if it is non-const the assignment works normally.
One more question:
const int *ptr = malloc(4 * sizeof(int));
free(ptr); /* gives warning */

While freeing the memory, the compiler generated warning. What is the
reason behind that ? Can't this memory be freed ?

When you free() a block of memory, you make it available
for re-use by a subsequent malloc(). Even if free() itself
does not modify the memory block, it exposes the block to
being modified later on. Hence, free(ptr) violates the promise
not to use ptr to modify the memory it points at.

You can still free() the memory, but not by using ptr as
it stands. One way is

free ((void*)ptr);

Even though ptr is const-qualified, (void*)ptr is not. See
the change to line #2 in the earlier example.
Thanks Eric for your reply. What I got from your reply is that, if we
are trying to change any const value directly, the compiler will give
error and the code will not be compiled. Secondly, the const value may
be changed indirectly by some other ways, but in that case the
behaviour is undefined ( An implementation may put the const thing in
read only section and while changing it during run time through
indirect ways, it might cause a trap ).

The other thing that I wanted to know whether,
const int *cptr;
int *ptr;
have different types ? Can we convert one type to other without a cast
?

Also, what's wrong in doing,
void *ptr;
const int *ptr1;
ptr = ptr1;
I believe, "void *" is a generic pointer and any pointer type may be
converted to void pointer without cast. Then, why compiler generates
warning while doing "ptr = ptr1" ?

Also, what is the difference between "unqualifie d type" and "qualified
version of its type" ?

Dec 30 '06 #4
ju**********@ya hoo.co.in wrote:
[...]

The other thing that I wanted to know whether,
const int *cptr;
int *ptr;
have different types?
They have different types: "const-qualified pointer to int"
and "pointer to int," respectively.
Can we convert one type to other without a cast?
`cptr = ptr' is fine ("adding" a qualifier is all right),
but `ptr = cptr' is not ("subtractin g" a qualifier needs a cast).
Also, what's wrong in doing,
void *ptr;
const int *ptr1;
ptr = ptr1;
I believe, "void *" is a generic pointer and any pointer type may be
converted to void pointer without cast. Then, why compiler generates
warning while doing "ptr = ptr1" ?
Because you're trying to "subtract" the const qualifier.

const void *ptr2;
ptr2 = ptr1;

would be fine.
Also, what is the difference between "unqualifie d type" and "qualified
version of its type" ?
A "qualified" type has one or more "qualifiers " -- const,
restrict, and/or volatile -- while an unqualified type has none.
A qualified type has the same representation, same universe of
values, same alignment requirements, blah, blah, blah, as the
corresponding unqualified type, but the qualifiers specify
"special handling" of various kinds.

--
Eric Sosman
es*****@acm-dot-org.invalid

Dec 30 '06 #5

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

Similar topics

31
2413
by: Ben | last post by:
For many times, I've found myself changing my member variables from const back to non-const. No matter how good the original objective was, there was always at least one reason not to use const members. (swap, storing it in a container, etc.) Whereas in Java, 80% of the case, I would want "final" for my instance variables. It makes me think that is "const member variable" ever useful in C++? Maybe because of the value semantics of C++...
3
3049
by: Zeng Dinghao | last post by:
char c = 'd'; const char cc = 'd'; char* pc = "dfdfdf"; const char* pcc = "dfdfdf"; char const* cpc = "dfdf"; cout << typeid(c).name() << endl; cout << typeid(cc).name() << endl; cout << typeid(pc).name() << endl; cout << typeid(pcc).name() << endl;
4
1636
by: Pelle Beckman | last post by:
Hi, I saw this code in an earlier post (not that there's anything wrong with it) #include <iostream> using std::cout; const int hour = 3600; const int min = 60;
16
41768
by: herbertF | last post by:
Hi guys, In a program (not my own) I encountered the declaration of a constant pointer to an array consisting of two other const pointers to arrays. Not quite sure why they do it so complicated, but is it legal? Most compilers accept it, but one doesn't recognize the rhs as a constant. What are the requirements for the rhs in the declaration of a const pointer? Is the following program legal C? int main(int argc, char *argv) {
20
17338
by: Chris | last post by:
Hi, can you define const-functions in C# as in C++ ? for example (C++-code) : int Cube :: GetSide() const { return m_side; }
1
1727
by: Stabiplan BV | last post by:
Hi, I am trying to find const variables outside a class. Thur far I did not succeed. Without const, the variable is found but with const not. So, how can I get hold on global const variables using reflection? Regards, Rob
4
3302
by: Rui.Hu719 | last post by:
Hi, All: I read the following passage from a book: "There are three exceptions to the rule that headers should not contain definitions: classes, const objects whose value is known at compile time, and inline functions are all defined in headers. " Can someone explain to me why some of the const objects must be defined in the header file?
3
19265
by: sam_cit | last post by:
Hi Everyone, When a variable is declared as const, it is initialized along with the declaration, as modification later on is not possible. Having seen that, how about const variables in a class? Is it possible for a class to have const variables? As just declaring the class alone doesn't create any memory, only creation of objects results in memory allocation for the object. Thanks in advance!!!
23
2316
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
10
5962
by: Stephen Howe | last post by:
Hi Just going over some grey areas in my knowledge in C++: 1) If I have const int SomeConst = 1; in a header file, it is global, and it is included in multiple translations units, but it is unused, I know that it does not take up storage in the
0
8672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8890
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5859
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2322
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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

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