Dstang
Dstang

Reputation: 11

Removing break and continue statements

Can anyone recommend an alternative to my break and continue statements? I know it is good practice not to use them. I am thinking of using a do while however, that would make the condition messy. Is there a cleaner way of doing this? I am using C. Due to requirements I cannot have either of them.

int inCmpStr( char *a, char *b)
{   
    int i;
    for (i = 0 ; a[i] && b[i]; ++i){
        if (a[i] == b[i] || (a[i] ^ 32) == b[i]){
            continue;
        }
        else {
            break; 
        }
    }
    if(a[i] == b[i]){
        return 0;
    }
    if ((a[i] | 32) < (b[i] | 32)){
        return -1;
    }
    return 1;
}

Upvotes: 1

Views: 958

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 223747

This code:

for (start; X; increment)
    if (Y)
        continue;
    else
        break;

is equivalent to:

for (start; X && Y; increment)
    ;

Therefore, you can use:

int i;
for (i = 0; a[i] && b[i] && (a[i] == b[i] || (a[i] ^ 32) == b[i]); ++i)
    ;

Upvotes: 3

sundb
sundb

Reputation: 490

You can use sub function to avoid use break and continue.

int cmpChar(char a, char b) 
{
    if (a == b || (a ^ 32) == b) {
        return -1;
    }

    if (a == b) {
        return 0;
    }

    if ((a | 32) < (b | 32)){
        return -1;
    }

    return 1;
}

int inCmpStr( char *a, char *b)
{   
    int i;
    int result;

    for (i = 0 ; a[i] && b[i]; ++i){
        result = cmpChar(a[i], b[i]);
        if (result != -1) {
            return result;
        }
    }

    return 1;
}

Upvotes: 3

Related Questions