TITLE: Casts, lvalues, and assignment PROBLEM: sanjay@riokidder.com (Sanjay Patel) const int J = 4; const int* pj = &J; (int)(*pj) = 81; // allowed, casting Lvalue to non-const Shouldn't this be illegal? RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 23 Oct 94 [ ... ] The line in question is not legal because it attempts to assign to the result of a cast. You can look in K&R1 from 1978, in the C Standard of 1989, or in the ARM to find that the result of a cast is a value, not an lvalue, and may not be assigned to. You won't find anything in Meyers' book to contradict this. Some early C compilers allowed, probably by accident, assigning to the result of some types of casts. More recent compilers sometimes duplicate the bug on purpose to allow code to compile which incorrectly relies on the earlier compiler bug. (Pete Becker confirmed in another post this deliberate bug replication in the case of Borland C++.) One correct way to write the cast is this: *(int*)(pj) = 81; // cast const ptr to non-const ptr, then assign In C++ you can also cast an lvalue to a reference, and it is still an lvalue (special case for references): (int&)(*pj) = 81; // cast away the const "Casting away const" is in itself legal, since const and non-const versions of pointers must have the same representation -- this is true in C and C++. A pointer declared to point to const may in fact point to a non-const object; in that case casting away the const is safe. Meyers' book has examples of this. Assigning through a pointer after casting away const is valid if the object pointed to is not declared const. If the object is declared const, as in this example, the result of the assignment is undefined. "Undefined" means that you cannot in general predict what will happen, and no particular behavior is required of the compiler or runtime system. The compiler may diagnose an error, but need not; you might or might not get a memory fault at run time.