Complete.Org: Mailing Lists: Archives: freeciv-dev: January 2001:
[Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-warnings
Home

[Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-warnings

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: "SamBC" <sambc@xxxxxxxxxxxxxxxxxxx>
Cc: "freeciv development list" <freeciv-dev@xxxxxxxxxxx>
Subject: [Freeciv-Dev] Re: (offtopic) C subscripts; was Re: Compiler-warnings
From: Gaute B Strokkenes <gs234@xxxxxxxxx>
Date: 26 Jan 2001 17:24:24 +0000

On Fri, 26 Jan 2001, sambc@xxxxxxxxxxxxxxxxxxx wrote:


>> Incidentally, this means that [] is abelian:
> 
> This is the first time I have seen the new words I learnt on my
> first year maths (degree) course used anywhere else. Makes me feel
> special to understand it...

Congratulations; I'm a third-year maths student.  So we think alike...

>> int
>> main (int argc, char *argv[])
>> {
>>   printf("The third letter of the alphabet is %c.\n", 2["ABC"]);
>> }
> 
> Not sure if you're right though...

Oh, I'm right.  The above example will compile and run.

Also, from the comp.lang.c FAQ:

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

A:      Yes, array subscripting is commutative in C.  The array
        subscripting operation a[e] is defined as being identical to
        *((a)+(e)).

> I think some people are going odd on the thing about pointer
> arithmetic/subscripts... given that an array name and a pointer are
> the same thing,

No!  However, the compiler will make implicit casts between the two
(in most, but not all, circumstances).  Read the comp.lang.c FAQ.  I
think it should be required reading for everyone who wants to program
in C.

> you get the same results, excepting location in memory, with (excuse
> C++ code, point is the same in C)
> 
> char* p = new char[50];
> //initialise array
> cout << p[20];
> cout << *(p+20);
> 
> as you do with
> 
> char p[50];
> //initialise array
> cout << p[20];
> cout << *(p+20);
> 
> and both should give unexpected results (or possibly errors) with
> 
> cout << p[-1];
> 
> as with
> 
> cout << *(p-1);
> 
> as well as with
> 
> cout << p[51];

No need to go to 51.  Remember, for an array of size x > 0, the
indices ranges from 0 through x - 1.

> and
> 
> cout << *(p+51);
> 
> Sory if someone else said this, or if I misunderstood... I'm a
> little behind, a little out of practise, and a little tired...

You're invoking undefined behaviour above, in both cases.  So I'm not
really sure what you're trying to say.

-- 
Big Gaute                               http://www.srcf.ucam.org/~gs234/
WHO sees a BEACH BUNNY sobbing on a SHAG RUG?!



[Prev in Thread] Current Thread [Next in Thread]