I've got a better code snippet: your exact same code snippet but for a language which will short circuit based on the lvalue of the assignment expression.
Then t would never be able to overflow s (nor even eat its null terminator)
At the time the code was written, the security ramifications were not quite the same as they are now. Even now, I would suggest that there are times where such a construction would be just fine.
This kind of code is cute, but awful for readability. The author could easily (more easily!) have written the function to be very readable, but went for the cute ultra-compact style instead. The only reason it's at all readable is that it's solving such a simple problem. Write more complex functionality in that style, and you quickly get a nightmare. I believe MISRA C outright bans this kind of thing (three assignments with no sequence point), as it has no place in a codebase of real consequence. I understand that some C programmers pride themselves on being able to read this kind of code (far more impressive than being able to write it), but I see no reason for it in serious software work.
Comments (380) 116 threads
Show all comments
Showing thread 9 of 116
Then t would never be able to overflow s (nor even eat its null terminator)
The things you listed are general concerns in C which are unrelated to both the correct implementation and the suggested changes.
Continue this thread — 4 replies
I wonder how much damage that code has caused.
This kind of code is cute, but awful for readability. The author could easily (more easily!) have written the function to be very readable, but went for the cute ultra-compact style instead.
The only reason it's at all readable is that it's solving such a simple problem. Write more complex functionality in that style, and you quickly get a nightmare.
I believe MISRA C outright bans this kind of thing (three assignments with no sequence point), as it has no place in a codebase of real consequence.
I understand that some C programmers pride themselves on being able to read this kind of code (far more impressive than being able to write it), but I see no reason for it in serious software work.