Home > Net >  I am trying to make a code that shows how many letters are in a string and im getting an error
I am trying to make a code that shows how many letters are in a string and im getting an error

Time:10-14

the error:

error: relational comparison result unused [-Werror,-Wunused-comparison]

for (int i = 0; (length = strlen(text)); i < length; i  )

                                         ~~^~~~~~~~

My code:

for (int i = 0; (length = strlen(text)); i < length; i  )
{
    if (isalpha(text[i]))
    {
        letters  ;
    }
printf("Letters: %i\n", letters);
return letters;
}

CodePudding user response:

There are 3 sections in the for loop header: initialization, repeat condition, and update. You have 4 sections. It thinks your initialization of length is the condition, and the comparison i < length is the update (i is ignored since it's in an extra section).

If you want to initialize two variables, you can do them both in the initialization section, separated by comma.

for (int i = 0, length = strlen(text)); i < length; i  )

You can also just write i < strlen(text) as the condition, without setting a variable. As long as the loop doesn't modify text, most compilers will realize that the length doesn't change, so they'll optimize this to call strlen() just once.

Or you can use the condition text[i] != '\0' to stop when you reach the end, instead of getting the length first.

CodePudding user response:

As @Barmar noted, your for() statement has too many 'sections'. AND you've missed a curly brace marking the end of the for() code block... (Missing, too, is the start of the function... One can only guess...)

Even easier is this:

    for (int i = 0; text[i] != '\0'; i  ) // This does what strlen() does without a function call
    {
        if (isalpha(text[i]))
        {
            letters  ;
        }
    } // brace was missing..

    printf("Letters: %i\n", letters);

    return letters;
}

Curly braces can sometimes be clutter, and especially when indentation is off can lead to bugs.
This code can be made more streamlined leaving out unnecessary braces...

for (int i = 0; text[i] != '\0'; i  )
    if (isalpha(text[i]))
        letters  ;

And, the test again '\0' is often omitted, too...

for (int i = 0; text[i]; i  )
    if (isalpha(text[i]))
        letters  ;

And, sometimes incrementing an index variable can be 'buried' into the last use of that variable

for (int i = 0; text[i]; )
    if (isalpha(text[ i   ]))
        letters  ;

And, then, C's guarantee of 0 and 1 (false and true) resulting from conditionals can be used to eliminate a slow, branching conditional...

for (int i = 0; text[i]; )
    letters  = isalpha(text[ i   ]);

The beauty of the C language.

  • Related