-8
   int arr[5];

   arr++;                                                        
   arr+4;                  //compile with only this 
   printf("%u", arr);

Why is the C language compiler not able to compile with arr++ saying "lvalue required" but can compile successfully with arr+4? What is the lvalue concept with arr++ notation?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    `arr` is ultimately not an lvalue (since it's the result of decay), and you can only use the modifying increment operators on lvalues. There's no such restriction on addition (e.g. it's valid to say `1 + 1`). – Kerrek SB Aug 09 '17 at 16:13
  • 1
    post an entire program that others can compile and test. – laolux Aug 09 '17 at 16:13
  • Possible duplicate of [Is an array name a pointer?](https://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer) – Bo Persson Aug 10 '17 at 02:58

1 Answers1

3

When you use arr it can naturally decay to a pointer to its first element, i.e. it's equivalent to &arr[0].

When you do arr++ you attempt to modify this pointer (effectively doing arr = arr + 1). This is not possible, since the location of the array is fixed and can not be modified.

With arr + 4 you're doing pointer arithmetic. Here you add 4 to the decayed pointer, but you do not attempt to modify the pointer itself. This is equal to &arr[4] in fact.


There is another small problem in the code you show. I say small but I mean big.

With

printf("%u", arr);

you let the array decay to a pointer. Then you attempt to print this pointer using the "%u" format specifier. But that format specifier is to print int, not pointers. Mismatching format specifier and argument types leads to undefined behavior.

To pint a generic (void *) pointer you need to use the "%p" format, and cast the pointer to void *:

printf("%p", (void *) arr);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621