Why does this compile?

G

g36130

Hello!

I was wondering why the following C code compiles:

main()
{
int a[100];
int b= 4[a]; /* Looks like 4[a] is equivallent to a[4] ??? */
return b;
}

Any explanations/links that would help me understand this would be
welcome (I coundn't find that in the C standard).
Cheers
g
 
M

Mark Bluemel

Hello!

I was wondering why the following C code compiles:

main()
{
int a[100];
int b= 4[a]; /* Looks like 4[a] is equivallent to a[4] ??? */
return b;
}

Any explanations/links that would help me understand this would be
welcome (I coundn't find that in the C standard).

You could have found it in the C FAQ at http://www.c-faq.com/
It's question 6.11
 
V

vippstar

Hello!

I was wondering why the following C code compiles:

main()
{
int a[100];
int b= 4[a]; /* Looks like 4[a] is equivallent to a[4] ??? */
return b;

}

Any explanations/links that would help me understand this would be
welcome (I coundn't find that in the C standard).

You would better wonder why your code shouldn't compile.

main has to return int.
Evaluating uninitialized objects invokes undefined behavior.
As for your question, x[y] is equal to *(x + y), x+y == y+x.
 
M

Malcolm McLean

I was wondering why the following C code compiles:

main()
{
int a[100];
int b= 4[a]; /* Looks like 4[a] is equivallent to a[4] ??? */
return b;
}

Any explanations/links that would help me understand this would be
welcome (I coundn't find that in the C standard).
It's a silly quirk of the language.
Arrays can be treated as pointers in most contexts, and pointers as arrays.
a[4] = means *(a + 4). So it makes sense that 4[a] should mean *(4+a). But
to write that in code is rather pointless.
 
A

Army1987

vippstar said:
Hello!

I was wondering why the following C code compiles:

main()
{
int a[100];
int b= 4[a]; /* Looks like 4[a] is equivallent to a[4] ??? */
return b;

}
You would better wonder why your code shouldn't compile.

main has to return int.
main() is equivalent to int main() in C90.
Evaluating uninitialized objects invokes undefined behavior.
This doesn't mean it shouldn't compile.
 
K

Keith Thompson

Malcolm McLean said:
Arrays can be treated as pointers in most contexts, and pointers as arrays.

Um, sort of. Read section 6 of the comp.lang.c FAQ to understand what
this really means.
 

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

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,183
Latest member
OrderGlycoEase

Latest Threads

Top