C Precedence Question

Started by
5 comments, last by GameDev.net 18 years, 2 months ago
Given this function..... void strcpy4(char dest[], const char source[]) { while (*dest++ = *source++); } Does the increment from the ++ operator happen before the boolean test in the while or after? So when the source reaches '\0', the order is: 1. assignment of '\0' to destination 2. check for FALSE ('\0' is the equivalent of boolean false) 3. end the while without incrementing since it tests FALSE Is this correct? It doesn't do the increment prior to the boolean check, correct?
Advertisement
it does increment _after_ the check. what you have, however, isn't a boolean check it's an assignment.

boolean check is == not =

also if your arrays are different sizes, your app will crash

-me
Quote:Original post by Palidine
it does increment _after_ the check. what you have, however, isn't a boolean check it's an assignment.

boolean check is == not =

also if your arrays are different sizes, your app will crash

-me


It's a string copy function. It's actually meant to be an assignment. It takes advantage of the fact I can do a boolean check this way. It's not checking the equality of the two strings in comparison, it's copying source to destination and breaking when it hits '\0', which is logical false.
P.S. I'm only using this tortured syntax to understand precedence, not to write a real function in a real program.
i++: i is incremented after use
++i: i is incremented before use.

Hope that answers your question :)
Quote:Original post by Spoonbender
i++: i is incremented after use
++i: i is incremented before use.

Hope that answers your question :)


Yup, thanks. Just wanted to make sure nothing funky was happening. Sometimes a bit of code will work in a compiler even though it's breaking the C rules.
Yeah, that's pretty much the canonical way to implement strcpy() in C.

This topic is closed to new replies.

Advertisement