473,805 Members | 2,191 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
18 5415
Keith Thompson wrote:
If compatibility were not an issue, would you really want both
array[index] and index[array] to be valid? If so, why?


If by *really*, you're asking if I think it's important
that I should be able to write code with index[array],
I'd say, "No, not really".

But, one of the things that I like about both the K&R books
and the C89 standard, is that compared to other books and standards,
they're small. Making that particular construct illegal,
would just be another rule to learn.

If you know the rules about pointers,
but the only thing that you know about the array subscript operator
is that index[array], means *(index + array),
then you know or can construe
everything that there is to know about the array subscript operator.

--
pete
Nov 13 '05 #11
pete <pf*****@mindsp ring.com> writes:
Keith Thompson wrote:
If compatibility were not an issue, would you really want both
array[index] and index[array] to be valid? If so, why?


If by *really*, you're asking if I think it's important
that I should be able to write code with index[array],
I'd say, "No, not really".

But, one of the things that I like about both the K&R books
and the C89 standard, is that compared to other books and standards,
they're small. Making that particular construct illegal,
would just be another rule to learn.

If you know the rules about pointers,
but the only thing that you know about the array subscript operator
is that index[array], means *(index + array),
then you know or can construe
everything that there is to know about the array subscript operator.


I see your point, but I disagree.

I see "pointer + integer yields pointer" and "integer + pointer yields
pointer" as two different rules. If the left and right operands are
of vastly different types, I see no great virtue in commutativity. I
would have preferred "pointer + integer yields pointer" and "integer
plus pointer is illegal". Aside from reducing complexity and
eliminating the useless obfuscation of index[array], this would also
more closely parallel the rules for pointer subtraction: "pointer -
integer yields pointer" and "integer - pointer is illegal". (The
analogy is weakened by the existence of "pointer - pointer yields
integer"; oh, well.)

This overloading of the "+" operator is built into the language.
Languages that allow programmers to define their own operator
overloading typically use something that looks like (or is) a function
definition. The ones I'm familiar with don't automatically force
user-defined "+" to be commutative. For example, in Ada, a
declaration like
function "+"(Left: Ptr; Right: Integer) return Ptr;
would not imply a declaration like
function "+"(Left: Integer; Right: Ptr) return Ptr;
If you want both, you have to declare both. (Replace function "+"
with operator+ and turn the syntax inside out for C++.)

On the other hand, if you think of commutativity as being at the very
core of what addition is all about, it certainly makes sense for
"pointer + integer" and "integer + pointer" to mean the same thing --
but then you'd have trouble with some languages' use of an overloaded
"+" operator to denote string catenation.

In any case, backward compatibility trumps both our arguments, so you
win. 8-)}

--
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 #12
Keith Thompson wrote:

pete <pf*****@mindsp ring.com> writes:
Keith Thompson wrote:
If compatibility were not an issue, would you really want both
array[index] and index[array] to be valid? If so, why?


If by *really*, you're asking if I think it's important
that I should be able to write code with index[array],
I'd say, "No, not really".

But, one of the things that I like about both the K&R books
and the C89 standard, is that compared to other books and standards,
they're small. Making that particular construct illegal,
would just be another rule to learn.

If you know the rules about pointers,
but the only thing that you know about the array subscript operator
is that index[array], means *(index + array),
then you know or can construe
everything that there is to know about the array subscript operator.


I see your point, but I disagree.

I see "pointer + integer yields pointer" and "integer + pointer yields
pointer" as two different rules. If the left and right operands are
of vastly different types, I see no great virtue in commutativity. I
would have preferred "pointer + integer yields pointer" and "integer
plus pointer is illegal". Aside from reducing complexity and
eliminating the useless obfuscation of index[array], this would also
more closely parallel the rules for pointer subtraction: "pointer -
integer yields pointer" and "integer - pointer is illegal". (The
analogy is weakened by the existence of "pointer - pointer yields
integer"; oh, well.)


Sometimes you can get a simpler looking expression by
putting the integer first.
You can write
(size_1 - size_2 + array)
when (size_1) exceeds the size of the array,
and (size_1 - size_2) doesn't.

But if you want pointer first, then you have to use parentheses:
(array + (size_1 - size_2))

--
pete
Nov 13 '05 #13
pete <pf*****@mindsp ring.com> writes:
[...]
Sometimes you can get a simpler looking expression by
putting the integer first.
You can write
(size_1 - size_2 + array)
when (size_1) exceeds the size of the array,
and (size_1 - size_2) doesn't.

But if you want pointer first, then you have to use parentheses:
(array + (size_1 - size_2))


Hmm. Maybe it's just me, but the only way I can make sense of
(size_1 - size_2 + array) is by mentally transforming it to
(array + (size_1 - size_2)).

I think I store pointers in the left side of my brain and integers in
the right side of my brain. (Don't ask me where I store
floating-point values.)

--
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 #14
Keith Thompson wrote:
I think I store pointers in the left side of my brain and integers in
the right side of my brain. (Don't ask me where I store
floating-point values.)


Presumably, they float around the pointers.

--
Chris "electric hedgehog" Dollin
C FAQs at: http://www.faqs.org/faqs/by-newsgrou...mp.lang.c.html
C welcome: http://www.angelfire.com/ms3/bchambl...me_to_clc.html
Nov 13 '05 #15
Groovy hepcat Keith Thompson was jivin' on Wed, 16 Jul 2003 00:33:38
GMT in comp.lang.c.
Re: Array indexing's a cool scene! Dig it!
pete <pf*****@mindsp ring.com> writes:
Keith Thompson wrote:
> If compatibility were not an issue, would you really want both
> array[index] and index[array] to be valid? If so, why?
If by *really*, you're asking if I think it's important
that I should be able to write code with index[array],
I'd say, "No, not really".

But, one of the things that I like about both the K&R books
and the C89 standard, is that compared to other books and standards,
they're small. Making that particular construct illegal,
would just be another rule to learn.

If you know the rules about pointers,
but the only thing that you know about the array subscript operator
is that index[array], means *(index + array),
then you know or can construe
everything that there is to know about the array subscript operator.


I see your point, but I disagree.

I see "pointer + integer yields pointer" and "integer + pointer yields
pointer" as two different rules. If the left and right operands are


But they're not two different rules. A + B has always been equal to
B + A, and not just in C, but in mathematics and in real life.
If I hold a pencil in my right hand and an apple in my left hand,
I'm holding an apple and a pencil. OTOH, if I hold an apple in my
right hand and a pencil in my left, I'm holding an apple and a pencil.
It doesn't matter that the apple and the pencil are two completely
different types of objects; when they're added to gether, it doesn't
matter which is on the right and which is on the left; they're still
an apple and a pencil. So it is with pointer addition in C.
of vastly different types, I see no great virtue in commutativity. I
would have preferred "pointer + integer yields pointer" and "integer
plus pointer is illegal". Aside from reducing complexity and
How would that reduce complexity? It may increase complexity
eliminating the useless obfuscation of index[array], this would also
more closely parallel the rules for pointer subtraction: "pointer -
integer yields pointer" and "integer - pointer is illegal". (The
Subtraction is not commutative; not just with pointers and integers,
but any types (even the same type). (A - B) != (B - A) except when B
== A, no matter what their type(s).
Integer - pointer just doesn't make sense. Integer + pointer does,
however.
analogy is weakened by the existence of "pointer - pointer yields
integer"; oh, well.)
If pointer + integer yields pointer, then it makes perfect sense
that pointer - pointer yields integer (and that pointer - integer
yields pointer).
This overloading of the "+" operator is built into the language.
Languages that allow programmers to define their own operator
overloading typically use something that looks like (or is) a function
definition. The ones I'm familiar with don't automatically force
user-defined "+" to be commutative. For example, in Ada, a
declaration like
function "+"(Left: Ptr; Right: Integer) return Ptr;
would not imply a declaration like
function "+"(Left: Integer; Right: Ptr) return Ptr;
If you want both, you have to declare both. (Replace function "+"
with operator+ and turn the syntax inside out for C++.)
These are not really addition operators. They are a type of function
designed to do whatever the programmer writes them to do (within the
possibilities of the language, of course).
On the other hand, if you think of commutativity as being at the very
core of what addition is all about, it certainly makes sense for
"pointer + integer" and "integer + pointer" to mean the same thing --
Right. (We are talking about the inherent functionality of addition,
which is commutative in nature, not the "+" character.)
but then you'd have trouble with some languages' use of an overloaded
"+" operator to denote string catenation.
That's not addition, but concatenation. It uses the "+" character to
represent it, but it's not the same thing. It doesn't belong in this
discussion.
In any case, backward compatibility trumps both our arguments, so you
win. 8-)}


Common sense has alot to do with it too.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Nov 13 '05 #16
ph******@alphal ink.com.au.STOP .SPAM (Peter "Shaggy" Haywood) writes:
Groovy hepcat Keith Thompson was jivin' on Wed, 16 Jul 2003 00:33:38
GMT in comp.lang.c.
Re: Array indexing's a cool scene! Dig it! [...] If I hold a pencil in my right hand and an apple in my left hand,
I'm holding an apple and a pencil. OTOH, if I hold an apple in my
right hand and a pencil in my left, I'm holding an apple and a pencil.
It doesn't matter that the apple and the pencil are two completely
different types of objects; when they're added to gether, it doesn't
matter which is on the right and which is on the left; they're still
an apple and a pencil.
I think the apple/pencil analogy supports my position better than
yours. It can matter a great deal whether the pencil is in my left
hand or in my right hand. If I hold a pencil in my right hand,
there's some chance you'll be able to read what I write with it.

But of course that's a statement about your analogy, not about your
underlying argument.
So it is with pointer addition in C.
In C as it's currently defined, yes (and I'm not advocating a change).

[...] If pointer + integer yields pointer, then it makes perfect sense
that pointer - pointer yields integer (and that pointer - integer
yields pointer).
I agree completely.
This overloading of the "+" operator is built into the language.
Languages that allow programmers to define their own operator
overloading typically use something that looks like (or is) a function
definition. The ones I'm familiar with don't automatically force
user-defined "+" to be commutative. For example, in Ada, a
declaration like
function "+"(Left: Ptr; Right: Integer) return Ptr;
would not imply a declaration like
function "+"(Left: Integer; Right: Ptr) return Ptr;
If you want both, you have to declare both. (Replace function "+"
with operator+ and turn the syntax inside out for C++.)


These are not really addition operators. They are a type of function
designed to do whatever the programmer writes them to do (within the
possibilities of the language, of course).


The distinction between operators and functions is largely artificial.
In some languages, it's practically nonexistent.
On the other hand, if you think of commutativity as being at the very
core of what addition is all about, it certainly makes sense for
"pointer + integer" and "integer + pointer" to mean the same thing --


Right. (We are talking about the inherent functionality of addition,
which is commutative in nature, not the "+" character.)


Ok, so you think of addition as being *fundamentally* commutative. I
don't.

Computer science obviously borrowed the concept of addition from
mathematics. In both pure mathematics and programming, addition
(i.e., expressions of the form X + Y) is commonly overloaded, meaning
that the operands can be of a number of different types. In pure
mathematics, the operands can be integers, real numbers, rational
numbers, complex numbers, quaternions, vectors, matrices, etc. In
most programming languages, the operands can be integers (signed or
unsigned, various sizes), floating-point numbers (often of various
sizes), and sometimes complex numbers and various other
language-specific things.

Something that I've rarely seen in mathematics is an addition operator
whose operands are of different types. I suppose you could add a
point and a vector, yielding a point, but I don't recall that kind of
thing being referred to as an addition operation.

[...] Common sense has alot to do with it too.


Well, my common sense apparently differs a bit from yours. That's not
necessarily a bad thing.

(Some people's common sense might say that multiplication is always
commutative, but in mathematics it often isn't.)

--
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 #17

"Peter "Shaggy" Haywood" <ph******@alpha link.com.au.STO P.SPAM> wrote in
message news:3f******** ******@news.alp halink.com.au.. .

(snip)
Subtraction is not commutative; not just with pointers and integers,
but any types (even the same type). (A - B) != (B - A) except when B
== A, no matter what their type(s).
Integer - pointer just doesn't make sense. Integer + pointer does,
however.
analogy is weakened by the existence of "pointer - pointer yields
integer"; oh, well.)


If pointer + integer yields pointer, then it makes perfect sense
that pointer - pointer yields integer (and that pointer - integer
yields pointer).


The IBM OS/360 assembler allows the equivalent of integer-pointer, or
pointer+pointer . That is, address constants can have relocation factors
of -1, 0, 1, or 2. It isn't all that hard to do, though for C it would
require two extra data attributes.

Consider the following.

int i,j,*p,*q,*r;

The expressions p-q+r, or p+r-q are legal,

The expressions p+r-q, -q+p+r, i-q+p, or (i-q)+(p+j) are not, yet all these
mathematically yield a pointer or integer value.

It isn't especially obvious that p+r-q should be illegal while p-q+r is
legal, any more than the commutativity of pointer and integer addition.

Note that I am not arguing against the commutativity of pointer+integer .

-- glen

Nov 13 '05 #18
Keith Thompson <ks*@cts.com> wrote:
[...]
Something that I've rarely seen in mathematics is an addition operator
whose operands are of different types. I suppose you could add a
point and a vector, yielding a point, but I don't recall that kind of
thing being referred to as an addition operation.


If you think of it as "position + displacement = position", then it's
quite common - in physics, anyway. This is quite a strong analogy with
"pointer + integer = pointer" actually, if you think about it - in C,
pointers are effectively positions within arrays, and the integer is
being treated as a displacement between two array positions.

- Kevin.

Nov 13 '05 #19

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

Similar topics

6
2751
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
10188
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
5489
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
8199
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
6844
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
9718
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
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10369
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
10109
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...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3008
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.