Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is a variable in C++?

The standard says

A variable is introduced by the declaration of an object. The variable's name denotes the object.

But what does this definition actually mean?

Does a variable give a name to an object, i.e. are variables just a naming mechanism for otherwise anonymous objects? Or is a variable the name itself?

Or is a variable a named object in the sense that every variable is also an object?

Or is a variable just a "proxy" with a name that "delegates" all operations to the real object?

To confuse things further, many C++ books seem to treat variables and objects as synonyms.

What is your take on this?


About entities, quoting from the C++0x draft:

An entity is a value, object, reference, function [...]

Every name that denotes an entity is introduced by a declaration.

A variable is introduced by the declaration of an object

From these statements I draw the conclusion that a variable is a name and thus cannot be an object. This is really confusing the hell out of me :)

like image 324
fredoverflow Avatar asked May 27 '10 11:05

fredoverflow


1 Answers

Here's the definition from the C++17 standard:

A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable’s name, if any, denotes the reference or object.

My take on this, quite frankly, is that that's not really a definition. It tells us what introduces a variable, but it doesn't define what a variable is.

Consider, for example:

int foo = 42;

This is a declaration of an object, so it "introduces" a variable. But what is the variable? Is the object named foo a variable? I would have thought so, but the definition doesn't actually say that. Apparently the "variable" has a name (in this case "foo") and that name denotes the object. Since it has a name, presumably the name itself is not the variable. And it would have been easy enough to say that the variable is the object, rather than that the variable's name denotes the object, if that were the intent.

What is a "variable" in C++? I really don't know, and I don't believe it's possible to answer the question based on the wording in the standard. (And I'd like that to be corrected in a future edition.)

(The C standard deals with this by not defining "variable" and, for the most part, not using it except as an adjective or informally.)

like image 189
Keith Thompson Avatar answered Oct 24 '22 03:10

Keith Thompson