Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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++))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading