Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

L Value required as increment operator - C

Tags:

c

lvalue

I just got a question from my Friend.

#include<stdio.h>

void fun(int[][3]);

int main(void){
    int a[3][3]={1,2,3,4,5,6,7,8,9};

    fun(a);
    printf("\n%u",a);
    a++;//Ques 1

    printf("\n%u",a);
    printf("%d",a[2][1]-a[1][2]);

    return 0;
}

void fun(int a[][3]){
    ++a;//Ques 2
    a[1][1]++;
}

The line Ques 1 will throw an error of L value as 'a' is the name of a two dimensional array. But this is not happening with the case of line Ques 2.

Can any one clear this doubt?

like image 927
Arivarasan.K Avatar asked Aug 16 '16 15:08

Arivarasan.K


People also ask

What is lvalue required as increment operand?

The pre-increment operator requires an L-value as operand, hence the compiler throws an error. The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won't need L-value as operand. The expression -(++i) is valid.

What is the meaning of l value required in C?

This error occurs when we put constants on left hand side of = operator and variables on right hand side of it.


1 Answers

In Ques 1, a is an array and it will be converted to a non-lvalue pointer when used as operand of ++ operator and emit compile error.

In Ques 2, the argument int a[][3] is equivalent to int (*a)[3] and ++a is an increment of pointer variable, which is acceptable.

Quote from N1570 6.7.6.3 Function declarators (including prototypes), pargraph 7:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

like image 61
MikeCAT Avatar answered Sep 30 '22 09:09

MikeCAT