Home > front end >  Why are the brackets for a C array on the variable and not on the data type?
Why are the brackets for a C array on the variable and not on the data type?

Time:09-21

I have a Java background and am learning C . I have a language implementation / syntax decision question.

In Java, array declaration looks like this:

//generally   
type[] variableName;
//concretely
int[] intArray;

However, in C , it looks like this:

//generally
type variableName[size];
//concretely
int intArray[5];

The Java version makes sense to me, that the brackets should append the datatype. The variable is not an int, it's an int array, so we replace the int with int[].

In C , why are the brackets after the variable name?

(Further, C seems to agree with this when it comes to pointers. An int pointer is int* intPtr not int ptr*. What am I missing?)

CodePudding user response:

This is a legacy item from c which declares it in the same way. I think it is likely just how it was done when c was first created. In modern c we can avoid using static arrays or pointers. Your example could be written as:

std::array<int, 5> intArray;

which is both more descriptive and adds lots of benefits. See here for more details.

CodePudding user response:

An int pointer is int* intPtr not int ptr*

Note that int* ptr and int *ptr are the same. Moreover,

int* ptr, i;

This declares "integer pointer ptr", and "integer i".

In C, pointers and arrays are very similar, and sometimes interchangeable. You can write for example:

int a[SIZE], *b;
b = a;
b = memory-allocation...
b[0] = 123;

The language is meant to be very simple and flexible (and very easy to screw things up)

In C you should just stay away from this, if you can.

  • Related