tags:

views:

455

answers:

11

according to some tutorials i read a while back, the "const" declaration makes a variable "constant" ie it cannot change later.
But i find this const declaration abit inconveniencing since the compiler sometimes gives errors like
"cannot convert const int to int"
or something like that.

and i find myself cheating by removing it anyway.

question: assuming that i am careful about not changing a variable in my source code, can i happily forget about this const stuff?

Thanks in advance

+1  A: 

You can forget about it but isn't it nice if the compiler forces it upon you? That way, your "const" variables actually stay constant.

wheaties
+38  A: 

Are you serious? Why would you want to give up on such a useful feature just because you make a mistake sometimes? Better try and learn to avoid mistakes with const and you benefit from the great assistance it adds to ensure correctnes with your code.

Of course, you can say goodbye to all the help the language provides, and tell the compiler thereby not tell you about mistakes in your code anymore. Instead, you will have to ask the debugger later on where your bugs are. Not sure whether that's better.

Johannes Schaub - litb
+1 "You can let the compiler tell you now, or ask the debugger to tell you later." Very nice.
Beta
+1 Good answer. It's not only a great help at compile time, it's also a nice form of documentation. You can see which variables can change and which cannot, which can save you a lot of time when reading code.
Helper Method
+1 The only time I don't use const as much as possible is when existing S/W isn't const correct and I'm refactoring it to be const correct bit-by-bit. I'd much rather know right at compilation that I'm changing something I didn't intend.
Mark B
+6  A: 

If you are careful, yes. But it is human to err. Also, you do not give the compiler the opportunity to optimize around these constants.

The error message that you get is because you try to alter a const int. Simply assigning the value to a (non-const) int, you alter it as you want to.

Const helps you, try to sprinkle more of it around and listen to the compiler. That will help you produce better code.

e8johan
The compiler can generally not use the `const`-information as an aid when optimizing.
Andreas Brinck
@Andreas: true in general, though in practice I have seen code that benefited from a const declaration of an automatic variable. That was on an old-ish GCC, though, and a newer one spotted that the non-const variable was never actually modified and applied the same modification. In that case, the optimisation to use an immediate value instead of an integer register, which of course only works because my variable was initialized with a value the compiler could see. Rather than try to guess what the compiler can or can't do, in theory and in practice, I just use const when I can.
Steve Jessop
@Steve That's why I wrote 'generally' ;) I would say it's a general misconception that `const` helps the compiler optimize. You should certainly use it everywhere you can, but for different reasons.
Andreas Brinck
@Andreas: Sorry, I may not have made it clear that I do agree with you. My example was intended to show how feeble a situation it was that actually made an optimization difference: the compiler had the necessary information to optimize without const, as proved by the fact that a later version does so. It just wasn't smart enough. Optimisations where I'm smarter than the compiler are *very* late stage ;-)
Steve Jessop
+1  A: 

Its always optional. If its all your code sure you can forget it ( I wouldn't recommend it, because it protects you), but when you interact with others, you're essentially providing a contract for them that you won't change their object or calling a function does not change the state of your object. This can be invaluable when you are not familiar with other's code, or you don't have the source.

Steve
Not always optional. For example, const references act differently from non-const references.
Zan Lynx
its optional in the fact that you don't have to use it if you don't want to code with that style. Regardless of its merits.
Steve
+1  A: 

Even if you and everyone you work with never makes mistakes, the use of const in your method declarations helps to document your interface.

RickNotFred
" if you and everyone you work with never makes mistakes" Which, of course, is impossible.
John Dibling
+2  A: 

The idea behind using 'const' is specifically that you ensure compiler errors when attempting to alter a variable's value when it has been predetermined (by using const) that you do NOT want to do so. It's essentially built in error-checking, and is useful for many reasons.

This is especially valuable in cases such as an external interface and public methods as a way of guaranteeing the caller that a passed value will not be modified.

const also locks in the intent to not modify, and prevents accidental assignment.

While making const use mandatory is unnecessary, it is very useful and good practice.

Here's a useful explanation you may want to check out: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

KevenK
+9  A: 

In C++, "const" can a apply to a variable (making it unchangeable) or a function (rendering it unable to change other things).

My use of "const" is not just to prevent my code from changing my variable. It's to prevent some idiot's code from changing my variable (especially if the idiot is me six months from now) and to prevent my code from changing a critical variable some idiot left exposed (especially if the idiot was me six months ago).

Beta
And as god is my witness. I too, am that idiot.
Spike
const cannot be applied to a function, only a member function.If it's in a function, you are really applying it to the arguments of the function.class A {public: void f() const; // f cannot change members of A, ie const A* this;};void g(const A // the argument a is const
Dov
@Dov, true, const cannot apply to *all* functions, only to *member* functions. And even a const (member) function can change *some* other things. I was trying for brevity, not rigor.
Beta
A: 

Changing things that shouldn't be changed is one of the most common sources of error. It is therefore worthwhile specifying const because it prevents you from doing something wrong. Why would you want to give that up?

const double PI = 3.14159265358979;

PI=4; // generates a compiler error (good)

There are some problems with the c++ notation, because a constant can only be initialized, not assigned the first time, and sometimes, you don't have the value at initialization time.

class A {
private:
  const int num;
public:
  A(int x, int y) : num(0) { // oops, I don't yet know what num should be
    while ( ... ) {

    }
    num = ...;
  }
};

The way out of this one is to define a private function that computes the value of num but sometimes that means that instead of one clean block of code in the constructor, you are forced to split it into sections in awkward ways, just so you can initialize the variable.

class A {
private:
  const int num;
  int computeNum(int x, int y) { ... }
public:
  A(int x, int y) : num(f(x,y)) {
  }
};

Sometimes, you have a value that is generally supposed to be const, but you want to selectively override that when it semantically makes sense. For example, social security numbers don't change, unless your identity is stolen. So you have just one method, called createNewSSN() which changes the otherwise constant ssn

class Person {
private:
  const int ssn;
public:
  Person(int ssn_) : ssn(ssn_) {}

  void createNewSSN(int newssn) {
    log << "Changed SSN: " << ssn << " to " << newssn << "\n";
    *(int*)&ssn = newssn; // trust me, this is a special case....
  }
};
Dov
"Pi is exactly three!"
Emile Cormier
Beta
That "trick" is undefined behavior. I seriously hope your SSN's aren't manipulated like that.
jalf
This is bad advice for multiple reasons. First, if an SSN can change, then the member variable should not be const. Second, the `*(int*)` trick evokes undefined behavior. Third, if you don't know the value of a const member at construction time, then when the compiler gives you an error it is telling you your design is wrong. Its not telling you its time to become a compiler contortionist.
John Dibling
For all standard junkies the relevant passage is 7.1.5.1/4 "Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a constobject during its lifetime (3.8) results in undefined behavior."
Andreas Brinck
A: 

To answer your question first:

Yes, you can. But only if you are careful, and everyone else who uses your code from now to eternity is also careful.

So, on balance you are better off thinking about why you should make something const and when you should not.

Another technique for exploring why const makes a difference is to try to make everything const at first until you have valid reasons to change something, then, and only then, remove the minimum number of consts until it works again.

Glad to see you are thinking about the issue - its more than most do.

quamrana
+3  A: 

You lose some useful language features without const, especially regarding references. Consider:

void f(const MyClass& m);
void f(const int& i);

// ...

f(MyClass()); // OK, can pass temporary as const reference
f(5); // OK as well, 5 is a temporary int

If you consider the 'const' optional and get rid of it:

void f(MyClass& m);
void f(int& i);

// ...

f(MyClass()); // Error, cannot pass temporary as non-const reference
f(5); // Error, same as above
AshleysBrain
A: 

People usually face this problem when they start using the const keyword. Believe me, it really helps. Leave it to the compiler to take care of the cosntness of the variable, instead of you taking care to not alter its value anywhere.

webgenius