Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: int x[+30] is a valid declaration?

I have been studying arrays these days. I have come across a declaration of an array and initialization of its element in this manner :

int x[+30];
x[+1]=0;

This is confusing me a little. I have the concept in mind that when we write:

x[n]=0;

Then it means:

*(x+n)=0;

Then writing x[+1] would mean *(x++1) and this seems invalid. Please correct me for the mistake I am making in understanding this concept.

like image 768
utkarsh867 Avatar asked Feb 24 '16 15:02

utkarsh867


People also ask

Which is valid declaration in C?

signed is default in C. No need to declare it explicitly. Hence 2 would be the answer. All are valid.

What is the declaration in C?

A "declaration" establishes an association between a particular variable, function, or type and its attributes. Overview of Declarations gives the ANSI syntax for the declaration nonterminal. A declaration also specifies where and when an identifier can be accessed (the "linkage" of an identifier).

What is a int declaration?

For example, the declaration int count declares that count is an integer ( int ). Integers can have only whole number values (both positive and negative) and you can use the standard arithmetic operators ( + , - , and so on) on integers to perform the standard arithmetic operations (addition, subtraction, and so on).

Is int valid in C?

In C, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99. char - stores single characters, such as 'a' or 'B'.


2 Answers

x[n] means *((x)+(n)) (note the blackets) and x[+1] means *((x)+(+1)). This is valid.

N3337 5.2.1 Subscripting

The expression E1[E2] is identical (by definition) to *((E1)+(E2))

like image 121
MikeCAT Avatar answered Sep 27 '22 23:09

MikeCAT


The + Plus symbol can act as a Unary Operator. It usually has no effect, but the consequence is that it gets removed before the number is resolved. For example:

int x[+30];

Is converted to

int x[operator+(30)];

Which then becomes

int x[30];

Thus, this expression

x[+1] = 0;

Would simply resolve as

x[1] = 0;

It wouldn't resolve as *(x++1), especially since that's not valid syntax in c++.

like image 25
Xirema Avatar answered Sep 27 '22 22:09

Xirema