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?

4
  • 3
    That's not a function, that's a macro. And can you show the small program you used that gave you different answers? They should give the same. Commented Mar 27, 2013 at 5:13
  • 1
    I think it would take a psychic to know why they #defined arr() like that. Commented Mar 27, 2013 at 5:18
  • @Cornstalks its possible they wanted to decay the array to a pointer. However, that doesn't explain why they wanted a function-like macro Commented Mar 27, 2013 at 5:22
  • you could have used '#define arr() (value)' as well. Commented Mar 27, 2013 at 8:09

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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;
}

1 Comment

You should write value[11], as the string "0123456789" has actual length 11 including \0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.