Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I've often seen the terms immutable and const used interchangeably. However, from my (little) experience, the two differ a lot in the 'contract' they make in code:

Immutable makes the contract that this object will not change, whatsoever (e.g. Python tuples, Java strings).

Const makes the contract that in the scope of this variable it will not be modified (no promise whatsoever about what other threads might do to the object pointed to during this period, e.g. the C/C++ keyword).

Obviously, the two are not equivalent, unless the language is single-threaded (PHP), or has either linear or uniquness typing system (Clean, Mercury, ATS).

First, is my understanding of these two concepts correct?

Second, if there is a difference, why are they almost exclusively used interchangeably?

share|improve this question
1  
const doesn't exist in every language, and mutability and immutability doesn't exist in every language so making this language agonistic is not applicable. It is language specific only where these concepts apply. –  Jarrod Roberson May 21 '12 at 23:45
2  
Related, recommended reading: Kinds of Immutability (a few C# examples, but largely language-agnostic). Someone give Eric Lippert a medal. –  delnan May 22 '12 at 11:08
add comment

5 Answers

up vote 2 down vote accepted

I’ll speak to C++, where this difference is most relevant.

As you correctly note, immutable means that an object cannot change at all after its creation. This creation can of course occur at runtime, i.e., a const object is not necessarily a compile-time constant. In C++, an object is immutable if (1) and either (2) or (3) are met:

  1. It has no members declared mutable that are mutated by const member functions

  2. It is declared const

  3. const member functions do not use const_cast to remove const qualification in order to mutate any members

However, you could also consider access modifiers: if an operation internally mutates an instance, but has no effect on the state of the instance observable through its public interface, then the object is “logically immutable”.

So C++ provides the tools necessary to create immutable objects, but like most everything in C++, the tools are only minimally sufficient, and require diligence to actually use. The state of an instance is not necessarily confined to the instance member variables—because C++ does not provide a way to enforce referential transparency, it can include global or class state as well.

const also has another function in C++: to qualify references and pointers. A const reference may refer to a non-const object. It is legal (though not generally necessary or advisable) to use const_cast to mutate an object through a const reference, if and only if that object is declared non-const:

int        i = 4;         // Non-const object.
const int* p = &i;        // const pointer.

*const_cast<int*>(p) = 5; // Legal.

And of course it’s undefined behaviour to mutate a const object:

const int  i = 4;         // const object.
const int* p = &i;        // const pointer.

*const_cast<int*>(p) = 5; // Illegal.
share|improve this answer
add comment

Immutable objects are those that does not change state after creating it. For example;

string prefix = "Pre";
string postfix = "Post";
string myComplexStr = prefix + postfix;

In this example myComplexStr object is immutable but not constant because it's value is calculated. And it is immutable because it is a string and has a static length property and cannot change.

Const objects are generally used to identify some real constants whose values are known before compilation like Pi, "USA", "StackOverflow.com", port numbers and so on.

From this perspective Const is different from Immutable objects because their values are not calculated by the program.

But if you are talking about "const" keyword in C++, you can say that "const" is used to create immutable objects.

share|improve this answer
1  
const in C++ don't create immutable objects, it's only an access level. –  Klaim May 22 '12 at 10:18
    
Can you explain how "const double pi = 3.14" is not immutable? –  Mert May 22 '12 at 10:38
    
Well it depends on where it is. Lets say I do : "double* p_pi= const_cast<double*>( &pi ); *p_pi = 42;" for example. Then if pi is in the global space or namespace, I get a segmentation fault, but it is, I believe, undefined behaviour, not a specific error. If pi is a member of any object that is available at runtime, that are not static, I get pi == 42. You see, even using mutable is available because const in C++ is about access level, semantic, not data immutability, that is almost impossible to achieve in C++. You can only "simulate" it. const is not immutable. –  Klaim May 22 '12 at 10:57
1  
@Klaim Mutating a const like that is undefined behaviour no matter where it's allocated, IIRC. And undefined behaviour is worse than any specific error guaranteed to happen. It means you don't use C++ any more - C++ provides no means to change a const value (except mutable members of course, but that isn't your point), so as far as C++ is concerned, you cannot do it. What specific implementations happen to allow is another matter entirely (and I bet you, if you compile with optimizations, the stunt you pulled won't affect later expressions using pi because it's been substituted). –  delnan May 22 '12 at 11:04
    
"const in C++ don't create immutable objects" is still wrong because it still creates global constants as you stated in your own answer. The keyword is ofcourse semantic at some level, otherwise you could always just manually change a memory cell's voltage and change an immutable object's value if you are so eager to even use undefined behaviours. –  Mert May 22 '12 at 11:05
add comment

Speaking for Java where the keyword "final" represents "const", consider:

final Person someone = new Person();

This means someone can NEVER refer to another Person object. But, you can still change details of the person being referred. E.g. someone.setMonthlySalary(10000);

But, if someone was an "Immutable" object, one of the following would be true: (a) You would not have a method named setMonthlySalary (b) Calling setMonthlySalary would always throw an exception such as UnsupportedOperationException

share|improve this answer
add comment

First, is my understanding of these two concepts correct?

Yes but your second question shows that you don't understand these differences.

Second, if there is a difference, why are they almost exclusively used interchangeably?

const in C++ is only used for access level (it means "read-only"), not for immutability. It imply that the access itself is totally separate from the data. For example you could manipulate some data then expose it through a const reference. The access is read-only, but the data itself, as all the datam is mutable.

const only garantee access limitations, while immutability (like in D for example) imply really no way to change the data at whatever stage of the life of the object.

Now, you can simulate immutability in C++ by making sure some data are not possible to be accessed in any other way than const and make sure it is initialized then not touched anymore. But that's not a strong guarantee as languages like D gives you when you mark your data as immutable. The language make sure it is not possible at all to do any operation modifying that data, while in C++ you are still potentially able to change the data through const casting and mutability if really necessary.

In the end, it is not the same at all as it don't offer at all the same guarantees.

share|improve this answer
add comment

In C++ they are the same. Although you can change a const object if you have it's location in memory and OS permission to write to that memory.

share|improve this answer
1  
Actually that's an argument against them being the same: C++ simply has no immutable keyword or language support. And also, I'm assuming that the programmer utilises the language in a sane manner: otherwise, const, too, has absolutely no value. –  K.Steff May 21 '12 at 23:21
1  
@K.Steff - perhaps better to say there is no extra immutable-ness in C++ other than provided by const –  Martin Beckett May 21 '12 at 23:23
    
Absolutely precise :) –  K.Steff May 21 '12 at 23:25
    
In C++ they are not the same at all. const is "read-only" access level, it don't mean that the data is immutable. You can bypass it in C++, most of the time. –  Klaim May 22 '12 at 10:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.