0

I'm having getting an error related to lvalue in this code:

#include <stdio.h>
#include<string.h>

main()
{
  int a[]={10,20,30,40,50};
  int j;
  for(j=0;j<5;j++)
  {
     printf("%d\n",a);
     a++;
  }
  return 0;
}

The error is displayed is:

lvalue is required as an increment operator.

Why is this problem occuring? Any help will be appreciated.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83

3 Answers3

3

You are trying to increment a int[] variable but that kind of variable doesn't support the increment operator.

If you were trying to iterate over the array you just need to use the variable used as the loop condition with the subscript operator:

for (int j = 0; j < 5; ++j)
  printf("%d\n",a[j]);

The main problem is that the ++x operator is semantically equivalent to x = x + 1, x. This requires x to be assignable (lvalue) (since you assign a new value to it) but an array is not assignable.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

In this expression

a++;

a temporary object of type int * is created that points to the first element of array a. You may not increment temporary objects. It is the same if you would write for example

int x = 10;

( x + 0 )++;

You could write the program the following way

#include <stdio.h>

int main()
{
  int a[] = { 10, 20, 30, 40, 50 };
  int *p;

  for ( p = a; p != a + sizeof( a ) / sizeof( *a ); ++p )
  {
     printf( "%d\n", *p );
     // or printf( "%p\n", p ); depending on what you want to output
  }

  return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

While it's true that arrays decays to pointers, an array is not a pointer, and you can't e.g. increment it.

Instead you can let it decay to a pointer by doing e.g.

printf("%d\n", *(a + j));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Why did you write `*(a + j)` instead of `a[j]` ? They're exactly equivalent; in both cases `a` decays. – M.M Jun 29 '14 at 14:57