Home > Net >  Why can not while(*s = *t ); be compiled after checking "out-of-bounds"?
Why can not while(*s = *t ); be compiled after checking "out-of-bounds"?

Time:05-20

I am currently learning "pointers by following the book "The C Programming Language" by Brian and Dennis.

I failed to compile:

#include <stdio.h>

void _strcpy(char *s, char *t)
{
    while(*s   = *t  )
        ;
}

And the error messages are:

warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
while(*s   = *t  )
      ~~~~~^~~~~~
55.c:5:16: note: place parentheses around the assignment to silence this warning
    while(*s   = *t  )
               ^
          (          )
55.c:5:16: note: use '==' to turn this assignment into an equality comparison
    while(*s   = *t  )
               ^
               ==
1 warning generated.
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

After trying to figure out what causes the errors, I think it might be the "out-of-bounds".

So, I tried this to test my assumption:

int main(void)
{
    char *t = "now is the time";
    char *s, *string = s;
    while(*s   = *t  );
    printf("%s", string);
}

Well, it still gave me the same error message above :(

Would it be the problem of the compiler?

I was using :

gcc -o [filename] [filename.c]

Could you help me out?

Thank you and have a lovely day!

CodePudding user response:

This is not an error but a warning.

Such a warning is meant to catch logical errors like this:

int found=0;
while (found=0) {
    // do something
    if (abc) {
        found = 1;
    }
}

Where an assignment was used when an equality comparison should have been used.

In your case, the assignment is intentional. So you can do as the warning suggests and put an extra set of parenthesis around the assignment to let the compiler know your intent.

while ((*s   = *t  ))
  • Related