Assignment operator += usage with earlier declared vs declared variable?

85 Views Asked by At

I am new to C and got a little confused. I have code where I am using += operator with a variable when declared but it is giving me an error for this operator, but working fine when used inversely i.e. =+. Please explain why?

Here is the code:

  int i = 0;
  int g = 99;
  do
  {
    int  f += i;   //Here += is throwing error and =+ is working fine why?
    printf("%-6s = %d ","This is",f);
    i++;
  } while(i<10);
Error as 
ff.c:16:11: error: invalid '+=' at end of declaration; did you mean '='?
    int f += i;
          ^~
          =
1 error generated.

It's working this way:

  int i = 0;
  int g = 99;
  do
  {
    int  f =+ i;   //Here += is `your text throwing error and =+ is working fine why?
    printf("%-6s = %d ","This is",f);
    i++;
  } while(i<10);
3

There are 3 best solutions below

2
Some programmer dude On BEST ANSWER

The definition

int f =+ 1;

is really the same as

int f = +1;

That is, you're initializing f with the value +1.

When initializing a variable on definition, you can only initialize it, not modify it.

0
0___________ On

+= is a special operator in C and it is something completely different that =+.

f += x adds x to f and stores it in f. It is the same as: f = f + x;

When you declare f you can't add anything to it as it does not exist at this point - thus error.

f=+1 assigns f with 1 as +1 == 1.

0
Ramy Nabil On

The operation

x += i;

is equivalent to

x = x + i;

So x should initially have a value before using the += operator and you can't use the += operator in the definition of a variable.