performance of pointers to access array elements

I am accessing array elements very frequently and want to optimise peformance as much as possible.

I would like to know exactly what the computer does with the syntax myarray[i] and how this compares to *(myarray+i). I know the answer is the same, but what about the process?

Also, what about passing arrays to functions? Ie. what is the difference between the following in terms of performance (all other things being equal):

void myfun(int myarray [])

void myfun(int myarray [N]) //N is the correct number of elements the array will contain

void myfun(int * myarray)

I would test this myself but I don't know how to implement a "stopwatch" in c++...
Last edited on
They are all identical (in both questions).
Well that simplifies that. Thanks Hamsterman.

So is there any real reason why one would specify the length of an input array in the function in put, ie. use void myfun(int myarray [N]) instead of void myfun(int myarray), or is it just used to improve readability for the coder?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const unsigned long N = 10;
void Modify1(int arr[N])
{
  for(unsigned long i = 0; i < N; ++i)
  {
    arr[i] *= i;
  }
}

void Modify2(int arr[])
{
  for(unsigned long i = 0; i < N; ++i)
  {
    arr[i] *= i;
  }
}

void Modify3(int *arr)
{
  for(unsigned long i = 0; i < N; ++i)
  {
    arr[i] *= i;
  }
}

int main()
{
  int arrA[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int arrB[5] = {0, 1, 2, 3, 4};

  Modify1(arrA); //Fine
  Modify2(arrA); //Fine
  Modify3(arrA); //Fine

  Modify1(arrB); //Wrong - Compile Error
  Modify2(arrB); //Wrong - No Compile Error
  Modify3(arrB); //Wrong - No Compile Error
}


Do you think a compile error would be useful to help catch a mistake? Trying to debug a crash or memory corruption is much harder ;)
That's actually not true @ LB

You don't get a compiler error in that case. You only get the error if you pass the array by reference:

1
2
3
4
5
6
7
8
9
void Modify4(int (&arr)[N])
{
 //...
}

//..
int arrB[5];
Modify1(arrB);  // no error
Modify4(arrB);  // THIS gives you an error 


AFAIK, putting in the 'N' when passing arrays normally makes absolutely no difference and is done so only for code readability.
Thanks for clearing this up.
Hm, I must have a funky compiler setting I don't know about then, as I do get the compile error :\
cannot convert from 'int [5]' to 'int [10]'
Compiles just fine here on VC++2010 Express
Topic archived. No new replies allowed.