Home > Software design >  Can we define 2 counters of different types in a single for loop statement in C and increase them?
Can we define 2 counters of different types in a single for loop statement in C and increase them?

Time:03-22

Can we use for statement like that? (C programming language)

for(int i = 0,double j = 2; i != j 134; i  , j = j 17);

I'm trying to learn linked list and I try to increase the index and set the pointer to next node just by using a single for:

for(node* current,int i = 0; current!=NULL; current=current->next_node, i  );

CodePudding user response:

What about?

struct IntDouble { int i; double j; };
for (struct IntDouble q = {0, 2}; q.i != q.j   134; q.i  , q.j  = 17) /* void */;

See code "running" at https://ideone.com/jEXBh7

CodePudding user response:

Opposite to C in C you may not declare objects in the if statement.

It seems you mean the for statement

for(int i = 0,double j = 2;i != j 134;i   , j = j 17);

instead of the if statement

if(int i = 0,double j = 2;i != j 134;i   , j = j 17);

However the syntax of this declaration

int i = 0,double j = 2;

is incorrect. You need to declare one of the variables before the for loop as for example

double j = 2;
for (int i = 0;i != j   134; i   , j  = 17 );

If the type specifiers would be common for both variables i and j (for example the type int) then you could write

for (int i = 0, j = 2;i != j   134; i   , j  = 17 );

The same approach should be used in this for loop where you forgot to initialize the pointer current

int i = 0;
for (node* current = head; current!=NULL; current=current->next_node,i  );

If you really mean to use the if statement then this line

if(node* current = head,int i = 0; current!=NULL; current=current->next_node,i  );

should be rewritten by you like

node *current = head;
int i = 0;

if ( current != NULL )
{
    current = current->next;
    i  ;
}
  •  Tags:  
  • c
  • Related