Search code examples
cassignment-operator

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


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);

Solution

  • 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.