-2

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
  • Which error is generated? Commented Aug 12, 2023 at 18:21
  • 4
    += is not the same as =+. Commented Aug 12, 2023 at 18:32
  • In ancient C history, the operators actually were =+ and =- initially. However, when writing this as f=-i they didn't know if it was meant to be f =- i or f = -i. So the assignment was changed to += and -= (over 50 years ago). Commented Aug 13, 2023 at 9:18

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So this int f = +1; means that f is being assigned value of 1 and nothing else right?
yes. same as >= is not the same as =>
1

+= 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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.