0

I'm wondering what the array subscripting operator ([]) do to objects

From this question and this question, I learnt that the [] operator takes an address of an object, adds whatever it is in between the brackets to the object and finally dereferences the sum to obtain an address. However, in array declarations, eg.

int iarr[] = {1,2};
int iarr2[2] = {1,2};

The [] operator doesn't seem to be adding the value in the brackets to the operand, especially in the second example. Instead, it seems to be giving the object the ability to store arrays.

Also, my wild guess is that in int arr2[2] = {1,2}, arr[2] will allocate memory for two ints. Is that true?

As a summary:

What does the [] operator do to its operand during declaration? Does it just give the object the ability to store arrays or does it allocated memory for the array instead?

2
  • 2
    The meaning of [] depends on the context but in your case it's not an operator. It's the syntax do declare or initialize an array. Commented Oct 14, 2019 at 11:35
  • 1
    Remember that C++ uses a Context-sensitive grammar. The same symbol often means different things in different contexts. Commented Oct 14, 2019 at 12:33

3 Answers 3

6

[] is an operator only when applied to an expression.
(The same principle holds for & and *.)

In a declaration, it's part of the type and doesn't really "do" anything other than specify that the declared variable is an array.

Sign up to request clarification or add additional context in comments.

Comments

2

You are confusing the [] operator and the syntax for declaring an array.

int iarr2[2] = {1,2};

is declaring an array named iarr2 of 2 integers and then initializing the elements of the array to 1 and 2. It is not applying the [] operator.

Comments

1

This:

int iarr[] = {1,2};

Means define an array which size will mach number of elements in initialization list.

On other hand:

 int iarr2[2] = {1,2};

Means define an two element array and initialize it to 1 and 2

You can do also:

 int iarr2[4] = {1,2};

Means define an four element array and initialize first two elements to 1 and 2. Remaining elements are initialized to: 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.