473,756 Members | 6,852 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

type of array index?


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?

OT: near as I can tell my implementation of gcc doesn't have an
<stddef.h> file with ptrdiff_t defined. Am I overlooking something?

--
Nov 14 '05 #1
29 5471
> what should be the type of 'k'? Should it be ptrdiff_t?

It should be any type of integer.

Jon
----
Learn to program using Linux assembly language
http://www.cafeshops.com/bartlettpublish.8640017
Nov 14 '05 #2
If you really want ptrdiff_t, it appears to be in malloc.h. stdint.h
has its limits. Interestingly, obstack.h thinks that it appears in
stddef.h, too. Perhaps someone should report that to the maintainers.
Using gcc 3.3.1.

Jon
----
Learn to program using Linux assembly language
http://www.cafeshops.com/bartlettpublish.8640017
Nov 14 '05 #3
sh********@ticn et.com wrote:
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?
Essentially, there are two choices:
1. Use int whenever sufficient, use a wider type when necessary.
Sufficient means sufficient with respect to the minimal requirements
from the standard.
2. Always use size_t.
size_t is sufficient for all arrays and for indexing all storage you
can allocate (bytewise).

Personally, I favor the second approach but I am not religious
about it. Drawbacks: You have to be more careful due to the inherent
nonnegativity of the index type, e.g.
for (i=MAX-1; i>=0; i--)
operation_on(ar ray[i]);
either has to become
for (i=MAX; i>0; i--)
operation_on(ar ray[i-1]);
or
for (i=MAX-1; i!=-1; i--)
operation_on(ar ray[i]);
which I like better.
As for int: It is possible that int indices are "faster" as int usually
is the "natural" integer type of the system but if this is really
the case, one can still optimise where necessary. Undefined behaviour
due to forgetting about "old-fashioned" 16 bit ints and resulting
strange errors are less nice.

However, there have been many discussions about that.
Do as you like and look for range/sanity checks as necessary (in both
cases).

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?
Any integer type which suffices for your range requirements.
I would use ptrdiff_t only where appropriate.

If ssize_t had made it into the standard, I'd suggest that.

OT: near as I can tell my implementation of gcc doesn't have an
<stddef.h> file with ptrdiff_t defined. Am I overlooking something?


That you cannot find it in the header file does not mean that
it is not there by some magic (or simply comes in from another
included file).

Just try it out:
If

#include <stddef.h>
int main (void) { int a[3]; ptrdiff_t b = (a+2)-(a+1); return 0; }

does not compile, file a bug report.
If it does compile without the #include, do the same.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #4
Jonathan Bartlett wrote:
If you really want ptrdiff_t, it appears to be in malloc.h. stdint.h
malloc.h is not a C standard header, thus offtopic.
has its limits. Interestingly, obstack.h thinks that it appears in
dito for obstack.h
stddef.h, too. Perhaps someone should report that to the maintainers.
Using gcc 3.3.1.


If including <stddef.h> has the effect that size_t or ptrdiff_t
are available when they were not before, everything is fine:
The implementation may do each and everything behind the scenes.

I did not yet have any problems with gcc's compliance in _this_
respect.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #5
sh********@ticn et.com wrote:
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?


It depends.

In concrete (non-generic) code the type is usually dictated by the
natural properties of the application area. You should normally have a
type that designates the total amount of objects of 'MYTYPE' already.
This type is an obvious candidate for the array index type. For example,
if this is an array of, say, file handles and you use 'unsigned short'
object to store the total number of files, then 'unsigned short' would
be a natural choice for the index type for this array. This, of course,
applies only if you don't care about negative indexing. For negative
indexing you'd have to use either 'short' or 'int', depending on the
required range.

In generic code 'ptrdiff_t' is the first candidate for array index type,
which also supports negative indices. If you don't care about negative
indices or you want to emphasize the fact that negative indices are not
allowed in some context, then you might want to go with 'size_t'. This
unsigned type is large enough for indexing of any array.

However, from the pedantic point of view, 'size_t' is intended to
implement a concept of "object size", while array index is more related
to the concept of "container element count". These two concepts are not
related and using 'size_t' for array indexing is a conceptual error. It
might be more elegant to "hide" the 'size_t' behind a typedef name as
follows

typedef size_t pos_ptrdiff_t;

and use 'pos_ptrdiff_t' for generic non-negative array indexing.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #6
Andrey Tarasevich wrote:
sh********@ticn et.com wrote:
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?

It depends.

In concrete (non-generic) code the type is usually dictated by the
natural properties of the application area. You should normally have a
type that designates the total amount of objects of 'MYTYPE' already.
This type is an obvious candidate for the array index type. For example,
if this is an array of, say, file handles and you use 'unsigned short'
object to store the total number of files, then 'unsigned short' would
be a natural choice for the index type for this array. This, of course,
applies only if you don't care about negative indexing. For negative
indexing you'd have to use either 'short' or 'int', depending on the
required range.

In generic code 'ptrdiff_t' is the first candidate for array index type,
which also supports negative indices. If you don't care about negative
indices or you want to emphasize the fact that negative indices are not
allowed in some context, then you might want to go with 'size_t'. This
unsigned type is large enough for indexing of any array.

However, from the pedantic point of view, 'size_t' is intended to
implement a concept of "object size", while array index is more related
to the concept of "container element count". These two concepts are not
related and using 'size_t' for array indexing is a conceptual error. It
might be more elegant to "hide" the 'size_t' behind a typedef name as
follows

typedef size_t pos_ptrdiff_t;

and use 'pos_ptrdiff_t' for generic non-negative array indexing.


Nicely put.
Something for a confessing size_t-user like me to think about :-)
Grabbed and stored.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #7
Jonathan Bartlett <jo*****@eskimo .com> writes:
If you really want ptrdiff_t, it appears to be in malloc.h. stdint.h
has its limits. Interestingly, obstack.h thinks that it appears in
stddef.h, too. Perhaps someone should report that to the
maintainers. Using gcc 3.3.1.


ptrdiff_t is declared in <stddef.h>. <malloc.h> is not a standard
header (the malloc() function is declared in <stdlib.h>), nor is
<obstack.h>. And <stdint.h> is a standard header in C99, but not in
C90, so not all current implementations will provide it (though it's
not too difficult to roll your own).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8
in comp.lang.c i read:
OT: near as I can tell my implementation of gcc doesn't have an
<stddef.h> file with ptrdiff_t defined. Am I overlooking something?


there is no requirement by the standard that a file exist -- it's allowed
to be magical, perhaps entirely internal. though in fact it does exist,
it's just that it's not where you are looking.

--
a signature
Nov 14 '05 #9
"Andrey Tarasevich" <an************ **@hotmail.com> wrote in message
news:11******** *****@news.supe rnews.com...
sh********@ticn et.com wrote:
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?
It depends.

.... In generic code 'ptrdiff_t' is the first candidate for array index type,
which also supports negative indices. If you don't care about negative
indices or you want to emphasize the fact that negative indices are not
allowed in some context, then you might want to go with 'size_t'. This
unsigned type is large enough for indexing of any array.

However, from the pedantic point of view, 'size_t' is intended to
implement a concept of "object size", while array index is more related
to the concept of "container element count". These two concepts are not
related and using 'size_t' for array indexing is a conceptual error.


Since an array is an object, and size_t is defined to be large enough to
represent the size of any object, size_t naturally must be able to represent
any possible array subscript.

In _The Standard C Library_, P. J. Plauger writes:

"Unlike ptrdiff_t, however, size_t is /very/ useful. It is the safest type
to represent any integer data object you use as an array subscript. You
don't have to worry if a small array evolves into a very large one as the
program changes. Subscript arithmetic will never overflow when performed in
type size_t." and "You should make a point of using type size_t /anywhere/
your program performs array subscripting or address arithmetic." (emphasis
in original)

The only reason one might prefer ptrdiff_t for array subscripts is where,
due to looping, you need the ability to count down past zero. In this case,
I would prefer ssize_t (where available) over ptrdiff_t, but first I'd
consider whether it was feasible to restructure the loop condition such that
a signed subscript wasn't needed.

S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin

Nov 14 '05 #10

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

Similar topics

4
10637
by: leslie_tighe | last post by:
Hello, I have a method on a com+ object that is returning an array of objects. I know the array is popluated as calls to check the ubound and lbound show valid values. However, any calls to get the value of a cell in the array results in a type mismatch error.
17
2448
by: benben | last post by:
Given a class template Vector<>, I would like to overload operator +. But I have a hard time deciding whether the return type should be Vector<U> or Vector<V>, as in: template <typename U, typename V> Vector<U_or_V> operator+ ( const Vector<U>&, const Vector<V>&);
1
1504
by: Allen Maki | last post by:
Why can I get the index of the item of the array when I use string*, but can not get the index of the array when I use any other type (such as Int32)? This code will compile perfectly, but if I replace String* with Int32, the code would not compile? The code using String* type: #include "stdafx.h"
51
23723
by: Pedro Graca | last post by:
I run into a strange warning (for me) today (I was trying to improve the score of the UVA #10018 Programming Challenge). $ gcc -W -Wall -std=c89 -pedantic -O2 10018-clc.c -o 10018-clc 10018-clc.c: In function `main': 10018-clc.c:22: warning: array subscript has type `char' I don't like warnings ... or casts.
669
26150
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
7
9837
by: Harris | last post by:
Dear all, I have the following codes: ====== public enum Enum_Value { Value0 = 0, Value1 = 10,
28
1949
by: VK | last post by:
A while ago I wrote a "Vector data type" script using DOM interface to select.options. That was a (beautiful) mind game :-) rather than a practical thing to use. Here is another attempt open for criticism, this time dead serious. I really need an effective Vector emulator for a project (as much effective as something not implemeted in language but emulated by means of the language itself is: a
3
1727
by: Hkan Johansson | last post by:
Being new to C# I wonder if the index of an array can be some other ordinal type than int? Coming from Delphi, I can determine the type of the index as well as the type of the elements, but haven't had any success with C# so far. The following example yields the compiler error: error CS0118: 'DemoClass.Months' is a 'type' but is used like a 'variable'. class DemoClass { enum Months {
26
8384
by: Szabolcs Nagy | last post by:
what type can/should be used as array index? eg. can i use unsigned long? or should it be size_t? example: int sum(int *a, index_t n) { int s = 0; index_t i;
0
9384
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9212
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,...
0
9973
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...
1
9779
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
9645
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
8645
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 projectplanning, coding, testing, and deploymentwithout 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...
1
7186
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
6473
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();...
2
3276
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.