0

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
CClarke
  • 503
  • 7
  • 18
  • 9
    Please **[edit]** your question with an [mre] or [SSCCE (Short, Self Contained, Correct Example)](http://sscce.org) – NathanOliver Jun 29 '20 at 21:33
  • Missing semicolons. – stark Jun 29 '20 at 21:53
  • In terms of context I've added my code and I think the title is quite clear. – CClarke Jun 29 '20 at 21:55
  • 3
    `int a....` is a definition. But you have already defined it. You want an expression instead. Remove `int`. – Eugene Sh. Jun 29 '20 at 22:00
  • 1
    The title is clear to an R programmer, because in R an assignment *is* a definition. In C, an assignment statement changes the value of an existing variable. It doesn't create a new variable, nor can it be used to change the type of an existing variable. – user3386109 Jun 29 '20 at 23:43

2 Answers2

4

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;
}
axiac
  • 68,258
  • 9
  • 99
  • 134
  • You are probably right. I didn't write C code this decade and I mixed them up a little bit :-( – axiac Jun 30 '20 at 07:43
2

The definition of a is done like:

int a;

The initialization of a is done like:

a = 10;

You do both in the same expression:

int a = 10;

Now a is defined and initialized.

If you do the following:

int a -= 5;

After the previous expresssion, you are redefining a, hence the error.

You need only:

a -= 5;
anastaciu
  • 23,467
  • 7
  • 28
  • 53