Checking for coding style aginst warning

During the compilation warning, I came across the following code:

char *strcpy(char *dest, char *src)
{
    unsigned int i;

    while( dest[i] = src[i] )//assignment in condition
        i++;

    return dest;
}

      

the basic function of the code should be OK, but the compiler warns that assignment in condition

, does this part of the code have any potential risks? if this kind of warning needs to be cleared?

+3


source to share


2 answers


All kinds of warnings must be cleared.

This warning was introduced because =

and is ==

often confused by programmers (hello, Pascal!), And your intent can be explicitly indicated by adding parentheses around the assignment expression:



if ((x = y)) // no warning

      

+4


source


No, you don't need to fix it.

The reason for the warning is that sometimes people mistakenly type =

when they mean ==

, for example.

while (response = 'n')

      

The assignment in the conditional expression is more likely to be an error than the assignment you want to check for, so the compiler warns about this. You can turn off the warning by wrapping the assignment in your test:



while ((dest[i] = src[i]) != 0)

      

On the other hand, I recommend always placing the body in while

or if

inside {}

, even if it's just one statement. See Why is it considered bad practice to omit curly braces?

You also need to initialize i

:

unsigned int i = 0;

      

+3


source







All Articles