In C is it allowed to use 2 variables in one line of a for loop?
This code does not compile.
#include<stdio.h>
int main(){
int arr[3][4]={
{0,3,5,2},
{2,13,4,6},
{7,33,12,5}
};
int i,j;
for (i=0,j=0;i++,j++;i<3, j<4){
printf("%d ", arr[i][j]);
}
}
>Solution :
It is OK to have as many variables as you wish in the for loop. The only problem with for (i=0,j=0;i++,j++;i<3, j<4) that the conditions are in the wrong place and you should use a logical operator as comma will simply take into account the last comparison.
for (i=0,j=0; i<3 && j<4;i++,j++)
Bear in mind that both variables will increment at the same time and it will not create two loops. So your loop will stop execute when i is equal to 3
int main(void)
{
for (int i=0, j=0; i<3 && j<4;i++,j++)
{
printf("i = %d, j = %d\n", i, j);
}
}
Result:
i = 0, j = 0
i = 1, j = 1
i = 2, j = 2
https://godbolt.org/z/P5oxsr9Wf