Search code examples
credefinitioncompound-assignment

How can you use compound assignment operators in C if you can't redefine variables?


Looking at wikipedia it says:

a -= b;

is the same as

a = a - b;

But when I try this in my C program I get the following error:

"error: redefinition of 'a'".

Here is my program:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a = 10;
    int a -= 5;

    printf("a has a value of %d\n", a);

    return 0;
}

I received the following errors:

my_prog.c:6:6: error: redefinition of 'a'
       int a -= 5; 
           ^
my_prog.c:5:6: note: previous definition is here
       int a = 10;
           ^
my_prog.c:6:8: error: invalid '-=' at end of declaration; did you mean >'='?
       int a -= 5; 
             ^~

I am using clang on Mac.


Solution

  • int a = 10 is a definition.

    It combines the declaration of variable name and type (int a) with its initialization (a = 10).

    The language does not allow multiple definitions of the same variable but it allows changing the value of a variable multiple times using an assignment operator (a = 10 or a = a - b or
    a -= b etc).

    Your code should be:

    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        int a = 10;    // declare variable `a` of type `int` and initialize it with 10
        a -= 5;        // subtract 5 from the value of `a` and store the result in `a`
    
        printf("a has a value of %d\n", a);
    
        return 0;
    }