Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the C++ variable declaration syntax inconsistent?

when I declare C++ variables, I do it like this:

int a,b,c,d;

or

string strA,strB,strC,strD;

I.e., first the type then a comma separated list of variable names.

However, I declare pointers like this:

int *a,*b,*c,*d;

and references like this:

int &a,&b,&c,&d;

To be consistent it should be

int* a,b,c,d;

and

int& a,b,c,d;

Why is it not consistent?

like image 249
MoShe Avatar asked Nov 01 '11 14:11

MoShe


People also ask

How do you declare a variable in C?

Declaring (Creating) Variablestype variableName = value; Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable.

Why do we need variable declaration in C?

The main purpose of variable declaration is to store the required data in the memory location in the form of variables so that we can use them in our program to perform any operation or task. By declaring a variable, we can use that variable in our program by using the variable name and their respective data type.

Where are variables declared in C?

The convention in C is has generally been to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first used.


1 Answers

The best answer I've seen as to why things like * apply to variables and not to types is the idea that declaration should follow use.

Basically, how you declare a variable should look similar to how you use a variable.

For example,

int *a, b;
...
*a = 42;
b = 314159;

...the use of a and b looks similar to the declaration of a and b.

There's even a citation for this behavior from Dennis Ritchie, one of the creators of C:

Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear...In all these cases the declaration of a variable resembles its usage in an expression whose type is the one named at the head of the declaration.

  • Dennis Ritchie, The Development of the C Language. History of Programming Languages-II ed. Thomas J. Bergin, Jr. and Richard G. Gibson, Jr. ACM Press (New York) and Addison-Wesley (Reading, Mass), 1996; ISBN 0-201-89502-1.
like image 83
Nate Kohl Avatar answered Sep 20 '22 00:09

Nate Kohl