From the course: Secure Coding in C

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Avoiding putchar() in a while loop

Avoiding putchar() in a while loop - C Tutorial

From the course: Secure Coding in C

Start my 1-month free trial

Avoiding putchar() in a while loop

- [Instructor] Using a functions return value as a condition in a loop is common, but better ways to code offer more predictability. This issue applies to both the getchar and putchar functions. In this code at line nine putchar appears as a condition in the while loop. The function output's a given character, but it returns that character's value, so the assumption is that the condition rings false, when the null character's encountered and returned, which happens at the end of the string, and coincidentally, terminates the loop. A better approach is to specifically test for the null character as shown in this improved version of the code, at line nine. The comparison is made specifically with a null character constant. This is a guarantee that the code runs as intended. Here's a pointer version of the same code. This is often the way I process a string, though it's subject to undefined behavior, the same as the…

Contents