2

I'm studying C programming ( with codeblocks IDE ) and I want to ask the following question :

Why is it wrong to write

int "i=j=0;"

rather than

"int i,j;

i=j=0;" or "int i=0,j=0;"
handlerFive
  • 870
  • 10
  • 23

3 Answers3

2

In the first case you never declare j. Either of the other two versions are fine as far as the C syntax goes.

However, it is considered good style (and this is subjective) to always declare every variable on a line of its own, and to never use multiple assignments in the same expression. Therefore I would personally recommend to do this instead:

int i=0;
int j=0;
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • In order to give more details, `=` operator in C have a right-to-left associativity, which means that `int i = j = 0;` is equivalent to `int i = (j = 0);`. Looking things that way shows that this line use but don't declare the variable `j` – DrosvarG Aug 08 '19 at 09:39
  • 1
    @DrosvarG One problem is that the = has no specified order of evaluation though, regardless of associativity. Which is one reason why it is better not to chain multiple = on a single line. – Lundin Aug 08 '19 at 09:41
1

The names need to be known before you can assign to them. Therefore, this is the closest thing to what you're looking to do:

int j;
int i = j = 1; /* OK, j is known */

When it comes to best practice, it's better to have them on separate lines as shown in Lundin's answer.

Andreas DM
  • 10,685
  • 6
  • 35
  • 62
  • There's actually a difference between `int i=0; int j=0;` and `int i; int j; i = j = 0;` In the first, both variables are *initialized* to zero. In the second, `0` is *assigned* to both variables. [They're not the same](https://stackoverflow.com/questions/35662831/initialization-vs-assignment-in-c), especially for complex types. – Andrew Henle Aug 08 '19 at 09:44
0

You don´t have declared j, so you will get an error because of an undeclared variable. A better way is to declare an variable in the following way:

int a, b;

Or if you want to set also the value:

int a, b = 1;
int a = 1, b = 1;
Kampi
  • 1,798
  • 18
  • 26