Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does const help the optimizer? C++ [duplicate]

Tags:

c++

constants

Possible Duplicate:
Constants and compiler optimization in C++

Let the holy wars begin: I've heard a number of differing opinions on the usefulness of const in C++. Of course it has uses in member function declarations, etc. But how useful is it as a modifier on variables (or rather, constants)? Does it indeed help the optimizer, if the rest of the code is left the same?

like image 612
bfops Avatar asked Oct 09 '10 15:10

bfops


People also ask

Does const improve performance C?

const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.

Does const optimize?

const can't be optimized because there may be other mutable references to the same memory object. But for immutable references, there cannot be. It is possible to cast away const and immutable in D, but these are only allowed in system code, presumably where the programmer actually does know what he's doing.

What does const in C do?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

Does const make a copy?

The const ness of arguments doesn't impact rather or not a copy is made. The fact that it's taken by value is what makes a copy.


1 Answers

There are a lot of cases where the const modifier won't help the optimizer, for the simple fact that the compiler can already tell if you modified a variable or not. The biggest benefit of const, in my opinion, is that it tells the compiler whether the programmer intended to modify that variable, which is useful in finding certain types of semantic errors at compile time instead of run time. Any error you can move to compile time is a huge boost in programmer productivity.

like image 145
Karl Bielefeldt Avatar answered Sep 18 '22 15:09

Karl Bielefeldt