Using "const"

I'm coming to C++ from Python and a little bit of C. The syntax has been a bit weird to me. It seems like the hierarchy of most C-like languages, by how high- or low- level they are, is C->C++->C#, etc->Python, etc., yet, C and Python have very closely related syntax, while C++ uses things like "std::cout >> text >> std::endl;" (Versus Python, using "print text"/"print "%s" % text", and C, using "puts(text);"/"printf("%s", text);". Python 3 is even more like C, with print being used as a function.) Declaring variables is something that, while not new to me, I am not used to. I've seen people use code like "const std::string text = "Hi."". They usually state their reason as something like "using the compiler to enforce not modifying that variable". To me, that seems like electrifying wet paint, or putting a layer of plastic, also covered in wet paint, over the wet paint. The compiler is just telling you something you would've found out anyway. Also, why would you WANT a variable to be un-modifiable? What would you use it for? Maybe as a constant for something like a physics engine? Even then, I would have an if statement to modify certain constants (not "const"'s.) by an input integer for insane physics mode. I read that it causes the compiled program to store the memory in a different section of the RAM, but this seems like something you would want to do when doing a final optimization. Why would you want to limit yourself from modifying a variable to increase performance before then? Also, how much of a performance increase could that actually GET you? To summarize, I want to know why anyone would use "const" when initializing a variable.
Last edited on
using 'const' or 'const correctness' as some people will put it is a way of informing anyone reading your code that the current value of this variable will not change throughout the lifetime of the program. It is mostly useful in a case where the code is being modified by someone other than the person who wrote it. The person modifying the code will see that word 'const' and immediately acknowledge that this variable is not to be assigned anything in the code or modified in any way.

I don't know about the compiler optimization thing you mentioned, but to anyone using 'const' in their code, I'm sure it is done with the intention of indicating that this variable does not change. This is equivalent to declaring variables with the 'static final' keyword in java.

In conclusion, think of const as tuples in python. Once declared, never modified
Last edited on
Re: const std::string text = "Hi."

The compiler is just telling you something you would've found out anyway.

The compiler is telling you nothing. You are telling the compiler that this string should be const.

Also, why would you WANT a variable to be un-modifiable? What would you use it for? Maybe as a constant for something like a physics engine?

Why wouldn't you?

I'm a little confused here. Are strings in Python not immutable (ie. const?) Python certainly has immutable variables (which are analogous to const variables.) How long have you been programming in Python? (Edit: Although I'm sure they use a term other than "variables" to describe them. The keyword "val" is used in Scala to indicate immutable values. I'm not as familiar with Python.)

If I want a guarantee that my string doesn't change, do you think I'm going to feed it to a function that takes a string by non-const reference? If the author of a function wants the caller to know there is a guarantee that a string fed to the function will not change, do you think he's going to take the parameter by non-const reference, or do you think the contract between the client code and the function should be enforced by the type of the parameters?


To summarize, I want to know why anyone would use "const" when initializing a variable.

For the obvious reason. To ensure it isn't modified.

Last edited on
I think I may have a gross misunderstanding of the concept discussed here. Does "const", by any chance, only prevent the data type from being changed? I was under the impression that it kept the value from being changed, too. Also, in Python, variable types are implied. You can have code like this:
1
2
3
4
5
6
var = 57
var2 = 3
print var, " + ", var2, " = ", var + var2
var = str(var)
var2 = str(var2)
print var, " + ", var2, " = ", var + var2

and the output would be:
1
2
57 + 3 = 60
57 + 3 = 573


Edit:
I reread your answers, and it seems "const" enforces the value not changing, too. I just can't think of any code where you would "accidentally" change the variable and not want it to be changed.
Last edited on
mckryall wrote:
I just can't think of any code where you would "accidentally" change the variable and not want it to be changed


Without const:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

bool PRINT = false;

int main() {
	string v = "Don't print this!";
	if (PRINT = true) // Whoops! Used assignment rather than comparison
	{
		cout << v << endl;
	}
	return 0;
}
Don't print this!


With const:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

const bool PRINT = false;

int main() {
	string v = "Don't print this!";
	if (PRINT = true) // Whoops! Used assignment rather than comparison
	{
		cout << v << endl;
	}
	return 0;
}

prog.cpp: In function ‘int main()’:
prog.cpp:9:12: error: assignment of read-only variable ‘PRINT’
  if (PRINT = true) // Whoops! Used assignment rather than comparison
            ^
prog.cpp:9:18: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
  if (PRINT = true) // Whoops! Used assignment rather than comparison
                  ^
Last edited on
Line 4 and line 5 do not modify the (immutable) objects that contained 57 or 3. They "point" var and var2 at different (immutable) objects.

See https://docs.python.org/2/reference/datamodel.html

The concept of "const" (if referred to by a different name) is equally useful in Python. Perhaps even more useful without the ability to pass objects by value.

Also helpful context:
http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
Smac89:
I can see what you mean, but that seems contrived.
EDIT:
In C++, can you not use "if (PRINT) {}", since it's a Boolean? That might just be in Python. I'll look it up.
EDIT EDIT:
Yup. You can use that. You could avoid your scenario entirely by just leaving out " == true".

cire:
I'll look into that, but I was just trying to show you know what background I was coming from.
Last edited on
Just to show another reason why I'm confused, here's a script in Python:
1
2
3
4
5
6
7
8
9
10
11
12
x = 1

def x_change(x):    
    x = 3
    print x

print x

x_change(x)

print x

Which outputs:
1
2
3
1
3
1
So 'x_change()' does not change 'x', that's confusing.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
void x_change(int &x){
   x = 3;
   std::cout << 3 << '\n';
}
int main(){
   int x = 1;
   std::cout << x << '\n';
   x_change(x);
   std::cout << x << '\n';
}
which outputs
1
3
3
Yeah, I could've given that function a better name. Now that I know what '&' does, I understand how to preserve the original variable value. If const is used to help make sure that you type "&", I can see how it would be useful. It's harder to keep variable passing straight than it is to type "==" vs. "=".
some variables should be const.
example:

1
2
const int daysOfWeek = 7;
const float PI=3.14;


You get the point...
I think I may have a gross misunderstanding of the concept discussed here. Does "const", by any chance, only prevent the data type from being changed? I was under the impression that it kept the value from being changed, too


I would like to point out that C++ and C are statically typed, meaning that data types in these languages are known at compile-time. This is why in C++ and C you have to specify the type. Python, on the other hand, is dynamically typed, which means its data types can be determined at runtime (think RTTI).

In C++, the keyword const refers to an immutable value and has nothing to do with changing the type. Instead, think of the const qualifier as being part of the type.
I think I may have a gross misunderstanding of the concept discussed here. Does "const", by any chance, only prevent the data type from being changed?


const doesn't prevent the data type from being changed. As the last post pointed out, const has nothing to do with type, const only makes the variable immutable i.e. the value doesn't (can't be) changed. Unless of course const_cast is used but let's just ignore that for now.

Also I don't understand the point you were trying to make with the function you posted, if you wanted to change the value of 'x', just put 'global x' in the function and the output will be the same as that of @ne555' output.
In most languages where objects are pass by reference (java, python, c#, c/c++ if working with pointers, etc ), most people assume that assigning that reference (or pointer) a different value changes the value of the object. What you don't realize is that the reference (or pointer) is pass-by-value. So in your example, you haven't really proven anything if your goal was to show that changing the value of x in the function doesn't change its value outside the function, because this is expected behavior.

In the code I posted, you can replace that bool with something like string and with the correct value and the example still holds.

Just rereading your first post and wanted to point out that although the compiler does enforce not changing the value of a const variable, the idea of const is lost after the program has been compiled into machine language (I might be wrong with this). At the machine language level i.e. 1's and 0's, there is no such thing as const; a value either exists or it doesn't. I point this out to show that there is no optimization going on by using const, it is just a way for the compiler to enforce that a variable is not to be modified for the duration of the program, and if this happens to produce code where that value is not modified, so be it. But after the compiler has finished, all that exists is just a value and if you have used a game cheat engine before, you know these values can be changed.
Last edited on
Topic archived. No new replies allowed.