Home > Blockchain >  Without using local variables, how could I loop through a c string stored in a character array so th
Without using local variables, how could I loop through a c string stored in a character array so th

Time:09-05

I'm trying to implement a bool function that returns true if a character c is within char array charset. However the given instructions specify that I am not to use local variables. I'm assuming local variables include those within for loops such as int i. Below is my current code using a for loop. If I'm not to use local variables, I know it would require a while loop, but my question then is what would be the condition of the while loop?

bool isInSet(char c, const char charset[]){
    
    for(int i = 0; i < 80; i  )
    {
        if(c == charset[i])
            return true;
        
    }
    return false;
}

CodePudding user response:

what would be the condition of the while loop?

The while loop could use the passed-in pointer as the loop condition.

bool isInSet(char c, const char charset[])
{
    while (*charset)  // loop until we find the terminating null character
    {
        if (*charset == c)
            return true;
          charset;  // go to next position
    }
    return false;
}

CodePudding user response:

Your char array is const, however if you can remove that const, you can use something like this:

while(*(charset) != '\0'){
    //your logic;
    charset  ;
}
  • Related