array perversion

M

matevzb

Since array subscripting is commutative in C, is the following
perversity legal and/or portable? (I don't really intend to use it
anywhere, it just puzzles my mind.)
#include <stdio.h>

int
fcn (void)
{
return 3;
}

int
main (void)
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 9 };

printf ("%d\n", fcn()[array]);
return 0;
}

It looks a bit confusing though, since the usage resembles the
following:
#include <stdio.h>

int *
fcn2 (void)
{
static int array2[] = { 5, 4, 3, 2, 1, 0 };
return array2;
}

int
main (void)
{
printf ("%d\n", fcn2()[3]);
return 0;
}
 
R

Richard Heathfield

matevzb said:
Since array subscripting is commutative in C, is the following
perversity legal and/or portable? (I don't really intend to use it
anywhere, it just puzzles my mind.)
#include <stdio.h>

int
fcn (void)
{
return 3;
}

int
main (void)
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 9 };

printf ("%d\n", fcn()[array]);

fcn() is basically 3, so you have 3[array], which is equivalent to array[3],
so yes, this is legal.
return 0;
}

It looks a bit confusing though, since the usage resembles the
following:
#include <stdio.h>

int *
fcn2 (void)
{
static int array2[] = { 5, 4, 3, 2, 1, 0 };
return array2;
}

int
main (void)
{
printf ("%d\n", fcn2()[3]);

Here, fcn2() is basically array2, so you've got *(array2 + 3), which is the
int value 2. Yes, that's legal too.


And either of them will get your legs chopped off if you produce them at the
Fagan inspection.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top