Search code examples
ccompiler-errorsmacrosc-preprocessorlvalue

C Expression must be a modifiable lvalue


I`m struggling with an error in C code.

#define MAX(i, limit) do \
{ \
if (i < limit) \
{ \
i++; \
} \
} while(1)
void main(void)
{ 
MAX(0,3);
}

This leads into the following error.

Error[Pe137]: expression must be a modifiable lvalue

Any ideas? Thank you in advance.


Solution

  • In this use case you try to increment 0 which is not possible.

    do {} while in this case makes no sense at all.

    I would write it this way :

    #define MAX(i, limit)  (((i) < (limit)) ? (i) + 1 : (i))  
    
    void main(void)
    { 
        int i = 5;
        i = MAX(i, 7);
        printf("%d\n", MAX(0,3));
        printf("%d\n", i);
        MAX(0,3);  // this statement has no effect
    }
    

    And (probably) you would not try to:

    0 = MAX(0,3);
    

    You need to remember that is the macro and i and limit will be evaluated as many times as they are in the macro. Example:

    #define MAX(i, limit)  (((i) < (limit)) ? i + 1 : i)
    
    int y = 1;
    int increase(void)
    {
        y++;
    }
    
    void main(void)
    { 
        printf("%d\n", MAX(increase(),3));
    }
    

    Some expressions may lead to the undefined behaviour:

    #include <stdio.h>
    #define MAX(i, limit)  (((i) < (limit)) ? i + 1 : i)
    
    int y = 1;
    
    void main(void)
    { 
        printf("%d\n", MAX(y++,3));
    }