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;"
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;"
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;
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.
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;