Use a pointer to one value as an array

(Note that the question has been expanded for "register" variables)

My question in a nutshell: Is this legal C code (to the letter of the standard for different insured ISO 9899 C - ideally with "proof" according to the standards):

int a = 0;
int b = (&a)[0];

const int c = 0;
b = (&c)[0];

      

Expanding on the question: This comment from Jens Gustedt suggests register variables are not allowed. It's true? Can you also provide additional quotation from the standards to speculate on this?

/* Question extension */
register int d = 0;
int e = (&d)[0];

      

Background:

I have a set of arrays representing the attributes of a structured set of objects - one array for each attribute. Thus, arrays are linearizations of this structured collection. These attribute elements of the attribute are compared with different values ​​depending on the position of the objects in the structured collection. These values ​​are also structured in a way that is related to the structure of the collection :-) Attribute arrays can be of different types.

So, I wrote a macro that iterates over all the attributes (given any of the attribute arrays) and provides information about the fly structure that can be used as an array index to compare arrays of values. This macro has an input: - an array of attributes - a comparison predicate - a comparative array of values ​​- and an index variable name for the array of values ​​(which is used to provide information about the structure in a rather complex loop inside the macro) - boolean to get the result

So, you can say something like:

COMP_ALL(attr1Arr,  <=, limitbyCath1Arr, cath1Idx, anyLimitFault)

      

and somewhere in a deep loop that linearizes over different categories, you find a comparison like:

anyLimitFault = anyLimitFault 
                  && (attr1Arr[objCounter]  <= limitbyCath1Arr[cath1Idx]);

      

Now sometimes there is only one limit value, so I want to write:

int limit = -1;
COMP_ALL(attr4Arr, <=, (&limit), 0, anyLimitFault);

      

Of course, I could always:

 int limit = -1;
 int temp[1];
 temp[0] = limit;

 COMP_ALL(attr4Arr, <=, temp, 0, anyLimitFault);

      

But I would prefer another way, so I can bind to:

 COMP_ALL2Value(attr_arr, pred, val, collector) \
      COMP_ALL(attr_arr, pred, (&val), 0, collector)

      

+3


source to share


2 answers


Yes. &a

in your example can be thought of as a pointer to the first element of a singleton array.



C99 / C11 §6.5.6 Additive Operators Section 7

For these operators, a pointer to an object that is not an element of the array behaves the same as a pointer to the first element of an array of length one with the object type as its element type.

+3


source


Yes.



Expression &x[0]

is just the equivalent of *(&x + 0)

which is the same as *(&x)

which is x

(for any variable x

, I believe).

+4


source







All Articles