473,796 Members | 2,707 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array indexing

The following code compiles with gcc 3.2.2 and Visual C++ 6:

#include <stdio.h>
int main()
{
int a[2] = {3, 4};
printf ("%d\n", 0[a]);
return 0;
}

The unusual part is the "0[a]". The compilers translate this to
"a[0]" with no warning. Has anyone else seen this behavior, or better
yet, can anyone explain it? It seems like "index[array]" is
equivalent to "array[index]".
Nov 13 '05 #1
18 5412
Joshua Neuheisel <jn********@msn .com> scribbled the following:
The following code compiles with gcc 3.2.2 and Visual C++ 6: #include <stdio.h>
int main()
{
int a[2] = {3, 4};
printf ("%d\n", 0[a]);
return 0;
} The unusual part is the "0[a]". The compilers translate this to
"a[0]" with no warning. Has anyone else seen this behavior, or better
yet, can anyone explain it? It seems like "index[array]" is
equivalent to "array[index]".


Yes, it certainly is. What's more, any expression such as "a[b]" is
equivalent to "b[a]" if exactly one of a, b is a pointer and the other
is a scalar integer.
This is a deliberate feature of C, and is completely standard, portable,
and safe. It's due to the fact that a[b] gets internally translated to
*(a+b), and + is commutative.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Remember: There are only three kinds of people - those who can count and those
who can't."
- Vampyra
Nov 13 '05 #2
Joshua Neuheisel wrote:
The following code compiles with gcc 3.2.2 and Visual C++ 6:

#include <stdio.h>
int main()
{
int a[2] = {3, 4};
printf ("%d\n", 0[a]);
return 0;
}

The unusual part is the "0[a]". The compilers translate this to
"a[0]" with no warning. Has anyone else seen this behavior, or better
yet, can anyone explain it? It seems like "index[array]" is
equivalent to "array[index]".


That actually makes sense.

Say &a[0] is 0x30000000

Then (int)a == 0x30000000 is valid.

Then 0[a] simply means *(&0 + a) which is *(0 + 0x30000000) == *(0x30000000)

Assuming that is what happened. And no, index[array] != array[index]
since index[array] will not multiply index by the sizeof array[0].

Tom

Nov 13 '05 #3
Tom St Denis wrote:
Assuming that is what happened. And no, index[array] != array[index]
since index[array] will not multiply index by the sizeof array[0].


Oops, it does.

Oh well.

Tom

Nov 13 '05 #4
jn********@msn. com (Joshua Neuheisel) writes:
The unusual part is the "0[a]". The compilers translate this to
"a[0]" with no warning.


This is in the FAQ.

6.11: I came across some "joke" code containing the "expression "
5["abcdef"] . How can this be legal C?

A: Yes, Virginia, array subscripting is commutative in C. This
curious fact follows from the pointer definition of array
subscripting, namely that a[e] is identical to *((a)+(e)), for
*any* two expressions a and e, as long as one of them is a
pointer expression and one is integral. This unsuspected
commutativity is often mentioned in C texts as if it were
something to be proud of, but it finds no useful application
outside of the Obfuscated C Contest (see question 20.36).

References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124,
Sec. 7.4.1 pp. 186-7.

--
"When in doubt, treat ``feature'' as a pejorative.
(Think of a hundred-bladed Swiss army knife.)"
--Kernighan and Plauger, _Software Tools_
Nov 13 '05 #5
In article
<Ni************ ********@news02 .bloor.is.net.c able.rogers.com >,
Tom St Denis <to********@iah u.ca> wrote:
Joshua Neuheisel wrote:
The following code compiles with gcc 3.2.2 and Visual C++ 6:

#include <stdio.h>
int main()
{
int a[2] = {3, 4};
printf ("%d\n", 0[a]);
return 0;
}

The unusual part is the "0[a]". The compilers translate this to
"a[0]" with no warning. Has anyone else seen this behavior, or better
yet, can anyone explain it? It seems like "index[array]" is
equivalent to "array[index]".


That actually makes sense.

Say &a[0] is 0x30000000

Then (int)a == 0x30000000 is valid.

Then 0[a] simply means *(&0 + a) which is *(0 + 0x30000000) == *(0x30000000)

Assuming that is what happened. And no, index[array] != array[index]
since index[array] will not multiply index by the sizeof array[0].


Tom, will you please get your copy of the C Standard out, read the
definition of the [] operator, think about it, and then post a
correction?
Nov 13 '05 #6
Ben Pfaff <bl*@cs.stanfor d.edu> writes:
[...]
6.11: I came across some "joke" code containing the "expression "
5["abcdef"] . How can this be legal C?

A: Yes, Virginia, array subscripting is commutative in C. This
curious fact follows from the pointer definition of array
subscripting, namely that a[e] is identical to *((a)+(e)), for
*any* two expressions a and e, as long as one of them is a
pointer expression and one is integral. This unsuspected
commutativity is often mentioned in C texts as if it were
something to be proud of, but it finds no useful application
outside of the Obfuscated C Contest (see question 20.36).

References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124,
Sec. 7.4.1 pp. 186-7.


Array subscripting is commutative because addition is commutative.

In most uses of the addition operator, the left and right operands are
of the same type. The exception to this is pointer arithmetic; you
can't sensibly add two pointers, but you can add a pointer and an
integer, yielding a pointer as the result. Both "pointer + integer"
and "integer + pointer" are legal and have the same meaning.

In my opinion, it would have been no loss to the language if the
pointer were required to be the left operand. Certainly there would
be no loss of expressive power. As a side effect of such a change,
array[index] would remain legal, but index[array] would become
illegal.

If you were to think of the various forms of "+" as overloaded
operators, declared with some function-like syntax, the
pointer+integer and integer+pointer forms would have to be declared as
two separate functions. Of course, C doesn't declare its operators
that way; the point is that allowing both forms adds to the
complexity.

I'm not advocating such a change now; the bureaucratic overhead would
exceed any benefit. But it's one of the many things that I would do
differently if I were designing a C-like language from scratch. (In
the process, of course, I would commit new and original design errors
that K&R never dreamed of.)

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #7
Keith Thompson wrote:
In my opinion, it would have been no loss to the language if the
pointer were required to be the left operand. Certainly there would
be no loss of expressive power. As a side effect of such a change,
array[index] would remain legal, but index[array] would become
illegal.

If you were to think of the various forms of "+" as overloaded
operators, declared with some function-like syntax, the
pointer+integer and integer+pointer forms would have to be declared as
two separate functions. Of course, C doesn't declare its operators
that way; the point is that allowing both forms adds to the
complexity.

I'm not advocating such a change now; the bureaucratic overhead would
exceed any benefit.
But it's one of the many things that I would do
differently if I were designing a C-like language from scratch. (In
the process, of course, I would commit new and original design errors
that K&R never dreamed of.)


Your opinion is missing the part which explains why you
want index[array] to be illegal.
What benefit?

--
pete
Nov 13 '05 #8
Tom St Denis wrote:

Joshua Neuheisel wrote:
The following code compiles with gcc 3.2.2 and Visual C++ 6:

#include <stdio.h>
int main()
{
int a[2] = {3, 4};
printf ("%d\n", 0[a]);
return 0;
}
Then 0[a] simply means *(&0 + a)


&0 isn't allowed.

--
pete
Nov 13 '05 #9
pete <pf*****@mindsp ring.com> writes:
Keith Thompson wrote:

[...]
I'm not advocating such a change now; the bureaucratic overhead would
exceed any benefit.
But it's one of the many things that I would do
differently if I were designing a C-like language from scratch. (In
the process, of course, I would commit new and original design errors
that K&R never dreamed of.)


Your opinion is missing the part which explains why you
want index[array] to be illegal.
What benefit?


What's the benefit of making such a counterintuitiv e construct legal?
As the C FAQ says, "This unsuspected commutativity is often mentioned
in C texts as if it were something to be proud of, but it finds no
useful application outside of the Obfuscated C Contest".

As I said, I'm not advocating making such a change, merely regretting
(mildly) that the feature was put into the language in the first
place.

If compatibility were not an issue, would you really want both
array[index] and index[array] to be valid? If so, why?

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2748
by: Michael Drumheller | last post by:
(If you're not interested in NumArray, please skip this message.) I am new to NumArray and I wonder if someone can help me with array-indexing. Here's the basic situation: Given a rank-2 array (i.e., a matrix) it seems to be trivial, with array indexing, to extract a subset of its *columns*. But it does not seem to be trivial to extract a subset of its *rows*. The code snippet below describes the problem (if it really is a problem)...
58
10186
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
9
15718
by: sangeetha | last post by:
Hello, Is there any performance difference in using of the following two declaration? int (*ptr); //Array of 10 int pointers int *ptr; // pointer-to-array of 10. Regards, Sangeetha.
29
5486
by: shmartonak | last post by:
For maximum portability what should the type of an array index be? Can any integer type be used safely? Or should I only use an unsigned type? Or what? If I'm using pointers to access array elements as *(mptr+k) where I've declared MYTYPE *mptr; what should be the type of 'k'? Should it be ptrdiff_t?
10
2070
by: Dennis Myrén | last post by:
Hi. I have an array of struct. My question is, if i do: STRUCT a = new STRUCT ; STRUCT s = new STRUCT(); a = s; since STRUCT is a value type, when assigning element 0 of the STRUCT array as above,
26
410
by: jacob navia | last post by:
Suppose an implementation where sizeof int == 4 sizeof void * == 8 sizeof long long == 8 When indexing an array array this would mean that arrays are limited to 2GB. To overcome this,
33
8196
by: Zytan | last post by:
I want to make a zero element array. I know that Nothing is not the same as a zero element array, since I can't get the length of, or iterate through, an array = Nothing. I could make a zero element array like this, but it seems like overkill: Dim emptyArray as Byte() = System.Text.Encoding.Default.GetBytes("") Is there a better way? Zytan
27
6726
by: Jess | last post by:
Hello, the following code failed with "segmentation fault". Could someone tell me why it failed please? Thanks! #include<iostream> #include<string> #include<cstring> #include<cstddef> using namespace std;
3
6843
by: Rüdiger Werner | last post by:
Hello! Out of curiosity and to learn a little bit about the numpy package i've tryed to implement a vectorised version of the 'Sieve of Zakiya'. While the code itself works fine it is astounding for me that the numpy Version is almost 7 times slower than the pure python version. I tryed to find out if i am doing something wrong but wasn't able to find any answer.
5
2682
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know if the structure contained only simple types (int, float) this will work without problems as you...
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9535
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10201
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9061
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6802
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2931
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.