Reputation: 1370
During clean compile warning, I met following code:
char *strcpy(char *dest, char *src)
{
unsigned int i;
while( dest[i] = src[i] )//assignment in condition
i++;
return dest;
}
the base function of the code should be OK, but compiler warn that the assignment in condition
, does this part of code have any potential risks? if this kind of warning need be cleaned?
Upvotes: 3
Views: 75
Reputation: 3000
All kinds of warnings need to be cleaned.
This warning was introduced because =
and ==
is often confused by programmers (hello, Pascal!), and your intent may be explicitly stated by adding parentheses around assignment expression:
if ((x = y)) // no warning
Upvotes: 4
Reputation: 782106
No, you don't need to fix this.
The reason for the warning is that sometimes people mistakenly type =
when they mean ==
, e.g.
while (response = 'n')
An assignment in a conditional is more likely to be a mistake like this than an assignment whose value you want to test, so the compiler warns about it. You can silence the warning by wrapping the assignment in a test:
while ((dest[i] = src[i]) != 0)
On the other hand, I recommend that you always put the body of a while
or if
inside {}
, even if it's just one statement. See Why is it considered a bad practice to omit curly braces?
You also need to initialize i
:
unsigned int i = 0;
Upvotes: 3