473,804 Members | 3,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const really constant?

Is const really constant?

And on an OT note: how can I post with a modified e-mail address so I
don't get so much spam?
Nov 13 '05
11 2380
On Sat, 20 Sep 2003, Arthur J. O'Dwyer wrote:

On Sat, 20 Sep 2003, Michael Winter wrote:

I believe the reason is that &x will return a pointer that is of type "const int *". As p doesn't have a const modifier, the assignment will be illegal.

That's correct. The address of an 'int' is a pointer to 'int'; the
address of a 'const int' is a pointer to 'const int'.
The cast attempts to remove that modifier before assignment. As

mentioned by others, this is undefined in C,


Not quite. The initialization

const int x = 42;
int *p = (int *)&x;

is absolutely legal in C. What's *not* legal is following that
up with

(*p) = 43;

because that tries to modify a const-qualified value. And
since it would be burdensome to make the compiler catch all
such errors, the standard simply calls the result of the
modification "undefined behavior" and leaves it at that.


I glossed over that. As I said, others mentioned what would occur if you
tried to modify a const-qualified variable through a pointer.
[OT from here...]
but quite legal as I understand (at least
with Microsoft's implementation) in C++.


I seriously doubt this. My impression is that C++ is *more*
strict about type-safety than C, not less.


That's a matter of debate. In addition to the C-style cast, C++ includes
four other casting operators.

dynamic_cast *is* strict - a run-time type check is performed on the
variable being cast [what checks, I'll omit]. If the cast fails, a bad_cast
exception is thrown.

static_cast checks the validity of the cast based on the information that
the developer provides (original and desired type). There was no mention of
exceptions in the case of a failure here, but there is the possibility of
undefined behaviour.

reinterpret_cas t allows you to convert any pointer into any other pointer -
there are no checks what-so-ever.

const_cast allows you to strip the const, volatile and __unaligned
attributes. Here, a write through a cast pointer (including one that was
previously const) *might* be undefined, but it depends on the type of
object. I don't have any more information on that: Microsoft's
documentation stops there (there was no "Microsoft-specific" marking, so I
assume that it is standard C++).

I do have to admit that I forgot the "might be undefined" part (I usually
stick to C-style casts, and I've never cast away a const-qualifier anyway).
However, it's not quite so clear cut as others present it in C, nor is C++
any more type-safe than C, unless the developer chooses to make it so with
the more reliable casts.

Mike

--
Michael Winter
M.Winter@[no-spam]blueyonder.co.u k (remove [no-spam] to reply)
Nov 13 '05 #11
On Sat, 20 Sep 2003 16:56:08 GMT, "Michael Winter"
<M.Winter@[no-spam]blueyonder.co.u k> wrote:
On Sat, 20 Sep 2003, Arthur J. O'Dwyer wrote: <snip>
Not quite. The initialization

const int x = 42;
int *p = (int *)&x;

is absolutely legal in C. What's *not* legal is following that
up with

(*p) = 43;

because that tries to modify a const-qualified value. And
since it would be burdensome to make the compiler catch all
such errors, the standard simply calls the result of the
modification "undefined behavior" and leaves it at that.

And just to be clear, any other storage or computation (assignment,
passing or returning, addtion/subtraction within an array) on the
deconstified pointer is legal; it is only dereference, or subscripting
which includes dereference, that is UB.
I glossed over that. As I said, others mentioned what would occur if you
tried to modify a const-qualified variable through a pointer.
If the pointer is to const, it is a constraint violation and diagnosed
(in C; in C++ it is a violation whose diagnosis is not waived, same
result). If the pointer has had const cast away, it is UB.

[OT from here...]
<snip>
I seriously doubt this. My impression is that C++ is *more*
strict about type-safety than C, not less.


That's a matter of debate. In addition to the C-style cast, C++ includes
four other casting operators. <snipped except>
If the [dynamic_cast] fails, a bad_cast exception is thrown.

For a reference; for a pointer it gives a null pointer.
const_cast allows you to strip the const, volatile and __unaligned
attributes. Here, a write through a cast pointer (including one that was
previously const) *might* be undefined, but it depends on the type of
object. I don't have any more information on that: Microsoft's
documentation stops there (there was no "Microsoft-specific" marking, so I
assume that it is standard C++).
It's standard, except for __unaligned as you might guess. Storing to
an object that was *defined* as const (and not mutable) is UB, as in
C: 7.1.5.1[dcl.type.cv]p4, as referenced by 5.2.11[expr.const.cast]p7,
and extended to deconstructed memory in 3.8[basic.life]p9; in C the
lifetime of an object is from allocation to deallocation, but in C++
for a nontrivial class type only from construction to destruction, so
this makes the const rule apply from allocation to deallocation.

If you create a const pointer to an object that is actually nonconst,
as can easily be done implicitly, then cast away const and store
through the result, that is well-defined and works in both C and C++.

Also, in C++ but not C a const variable of integer or enumeration type
initialized by a constant expression can be used in a constant
expression. This means that if you do illegally store to such a
variable, after/by forming a nonconst pointer to it, and the
implementation doesn't trap and actually does the store -- one
permitted option under UB -- it is rather likely that the stored value
will not be used in what appear to be subsequent fetches of it. A C
compiler may do this same optimization if it likes, under the (very)
broad aegis of UB, but it isn't encouraged the way C++ is.
I do have to admit that I forgot the "might be undefined" part (I usually
stick to C-style casts, and I've never cast away a const-qualifier anyway).
However, it's not quite so clear cut as others present it in C, nor is C++
any more type-safe than C, unless the developer chooses to make it so with
the more reliable casts.

It is in several places.

C++ does not allow implicit conversion from base to derived, which is
a feature that does not exist in C, but extends this principle to
prohibit implicit conversion of void* to any other data*, which C
allows; this is a FDiscussedFeatu re(?) on clc.

C++ considers enum types (and their values) distinct and does not
allow implicit conversion from an integer. C considers enums just
integers of some implementation-dependent size.

Optional arguments, and to some extent templates, allow some functions
with varying signatures to be written typesafely that would require
less-safe varargs in C, although that option still exists in C++.

C++ outlawed implicit int (and implicit function declaration) first,
but C99 has matched it. C++ has only the prototype syntax for
functions, not the less-safe K&R1 syntax still allowed in C.

C++ prohibited unvalued return for nonvoid functions first, but C99
has matched it; C++ also makes it UB immediately when falling off the
end of a nonvoid function, instead of trying to use the indeterminate
return value as in C, and this is often easier to diagnose though not
required. C++ also allows a return "value" of void type in a void
function, which is useful for templates, but not really needed in C.

C++ retains C's array/pointer duality and pointer arithmetic, which
are in practice impractical to make safe, but offers the option of
std::vector or other array-like classes and "smart" pointers, and in
particular std::string or other string classes for the area that has
proven most frequently (IMJ) troublesome in C.

But yes, the new more specific -- and more visible in source -- casts
are an important contributor to typesafety in C++.

- David.Thompson1 at worldnet.att.ne t
Nov 13 '05 #12

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

Similar topics

31
2439
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++...
5
1783
by: Kenneth Massey | last post by:
I have run into a peculiar problem, in which the following sample code does not compile (gcc 3.3). I have a template class with a member function that should take a const version of the template parameter. However, when I try to use the class with (T=int*), the compiler seems to ignore the const and gives an error if I pass a const int*. Any help would be much appreciated. Kenneth // test.cpp: In function `int main()':
16
41780
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) {
1
3919
by: electric sheep | last post by:
Hi, can somebody explain the following syntax to me. This is straight from a gnu info file: int main(void) { /* Hashed form of "GNU libc manual". */ const char *const pass = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/"; I think the idea at play here is whether the pointer is constant or not ?
4
3314
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?
14
6659
by: Tim H | last post by:
I understand the semantics of why this works the way it does. But I wonder if there's a reason for the behaviore at the line marked "QUESTION". I figured if there is an answer, someone here knows it. Specifically, part 1 is obvious to most anyone. Part 2 is isomorphic to part 1, yet behaves differently. If a shared_ptr is const, should it really allow non-const dereferences? Thanks,
26
2129
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 string 'hello' in first method lie in read-only memory and the string 'hello' in second method lie in a modifiable memory ?
23
2340
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
16
1927
by: arnuld | last post by:
I have declared an int as const but compiler still says that it is not a const: include <stdio.h> #include <stdlib.h> int main() { const int MAXSIZE = 100;
39
2798
by: Leonardo Korndorfer | last post by:
Hi, I'm litle confused by the const modifier, particularly when use const char* or char*. Some dude over here said it should be const char when you dont modify it content inside the function, I read somewhere that it when you won't modify after its initialization... So when exactly do I use one or another? Is it *wrong* not use const when I should?
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10331
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,...
0
10087
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7631
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
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
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
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.