Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange [1, 2] style array in C

Tags:

c

Was there a very early C "standard" where the following was legal for the definition of a two-dimensional array?

int array[const_x, const_y];
int array2[2, 10];

I've stumbled upon some old legacy code which uses this (and only this) notation for multi-dimensional arrays. The code is, except for this oddity, perfectly valid C (and surprisingly well-designed for the time).

As I didn't find any macros which convert between [,] and [][], and I assume it's not a form of practical joke, it seems that once upon a time there hath been thy olde C compiler which accepted this notation. Or did I miss something?

Edit: If it helps, it's for embedded microcontrollers (atmel). From experience I can tell, that embedded compilers are not that well-known for standard-compliance.

The code on current compilers works as intended (as far as it can be guessed from the function names, descriptions and variables) if I change all [,] to [][].

like image 504
vsz Avatar asked Jan 14 '13 04:01

vsz


2 Answers

The first formal standard was ANSI X3.159-1989, and the first informal standard would generally be agreed to be the first edition of Kernighan & Ritchie. Neither of these allowed the comma to be used to declare a two-dimensional array.

It appears to be an idiosyncracy of your particular compiler (one that renders it non-standard-conforming, since it would change the semantics of some conforming programs).

like image 102
caf Avatar answered Nov 19 '22 06:11

caf


Take a look at this forum post.

the comma operator evaluates the left hand side, discards the result, then evaluates the right hand side. Thus "2,5" is the same as "5", and "5,2" is the same as "2".

This could be what is happening, although the why of it is beyond me.

Note that comma cannot be used in indexing multidimensional array: the code A[i, j] evaluates to A[j] with the i discarded, instead of the correct A[i][j]. This differs from the syntax in Pascal, where A[i, j] is correct, and can be a source of errors.

From Wikipedia

like image 41
Karthik T Avatar answered Nov 19 '22 05:11

Karthik T