Arturo
Arturo

Reputation: 33

How can I translate this loop into a for loop?

I'm trying to convert this loop into a for loop, but I can't get it to work, it's in C.

while(args[argCounter]){
        if(!strcmp(args[argCounter], "|")){
            args[argCounter] = NULL;
            cmdbegin[child] = argCounter + 1;
            child++;
        }
        argCounter++;
}

Upvotes: 3

Views: 107

Answers (3)

0___________
0___________

Reputation: 67476

Or

char **tmp = args + argCounter;
for(;*tmp;tmp++)
{
    ++argcounter;
    if (!strcmp(*tmp, "|")) {
    *tmp = NULL;
    cmdbegin[child++] = argCounter;
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

I would translate it as follows:

for (int argCounter = 0 ; args[argCounter] ; argCounter++){
    if(!strcmp(args[argCounter], "|")){
        args[argCounter] = NULL;
        cmdbegin[child++] = argCounter + 1;
    }
}

I added declaration and initialization of argCounter which you did not show. The conversion was very much mechanical:

  • argCounter++ moved to the third "compartment" of the for loop header,
  • I moved child++ into the assignment to shorten the code somewhat; this is optional.

Upvotes: 1

chqrlie
chqrlie

Reputation: 144695

The initial value of argCounter is not specified in your code. Here is a conversion:

for (; args[argCounter]; argCounter++) {
    if (!strcmp(args[argCounter], "|")) {
        args[argCounter] = NULL;
        cmdbegin[child] = argCounter + 1;
        child++;
    }
}

If the loop starts at 0 and you want to make argCounter local to the for loop, here is a C99 version:

for (int argCounter = 0; args[argCounter]; argCounter++) {
    if (!strcmp(args[argCounter], "|")) {
        args[argCounter] = NULL;
        cmdbegin[child] = argCounter + 1;
        child++;
    }
}

Upvotes: 0

Related Questions