2

I am working on a project written in C programming language. I got a code snippet as below

unsigned char value[10];
#define arr() (&value[0])

Why have they defined a "function"(arr()) kind of #define'd variable for an unsigned char array?

They are trying to use the variable like arr()[1],arr()[2] etc.,

  1. Is arr() + 2 equal to value + 2. I tried executing a small program, but theses two results gave me different answers. how is it possible. Because they are assigning the address of first array to arr(). Should these two not be the same?

Can anyone explain what is the significance of defining a variable as above?

user1611753
  • 355
  • 1
  • 4
  • 9

4 Answers4

1

I can't tell you why they've done it, but yes, arr() + 2 and value + 2 are the same thing.

caf
  • 233,326
  • 40
  • 323
  • 462
1

This line #define arr() (&value[0]) means that whenever the preprocessor (which runs before the compiler) encounters arr() it replaces it in the file with (&value[0]).

So arr()[1] means (&value[0])[1]. value[0] is what's stored at the first index of value, & takes its address of it again... which is the same as value. So it should just be value[1] overall, unless I am missing something.

Patashu
  • 21,443
  • 3
  • 45
  • 53
1

arr()[i] ==> (&value[0])[i] ==> value[i]

Also

arr() + i ==> (&value[0]) + i ==> value + i

So

arr() + 2 ==> (&value[0]) + 2 ==> value + 2

I can only guess that programmer writing this way to make coding uniform with other part of hist code like this example

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
1

Is arr() + 2 equal to value + 2. I tried executing a small program, but these two results gave me different answers. how is it possible. Because they are assigning the address of first array to arr(). Should these two not be the same?

Yes they are the same.

Try this program

#include <stdio.h>

#define arr() (&value[0])

int main(void)
{

unsigned char value[11] = "0123456789";
printf("arr()[2] = %c\n",  arr()[2] );
printf("arr()+ 2 = %c\n",*(arr() + 2) );
printf("value+ 2 = %c\n",*(value + 2) );

return 0;
}
Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39
  • You should write `value[11]`, as the string `"0123456789"` has actual length `11` including `\0`. – Alex Mar 27 '13 at 07:11