From the course: Secure Coding in C

Unlock the full course today

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

Looping with floating point values

Looping with floating point values - C Tutorial

From the course: Secure Coding in C

Start my 1-month free trial

Looping with floating point values

- [Instructor] Loops are discrete things. They repeat a given number of times, always a whole number. Still for some reason, a programmer may use a floating point value to count in a for loop. This can lead to undefined behavior, such as in this code where the loop counter is based on 0.2, shown in the statement at line eight. Perhaps it's a graph that's being plotted or whatever, the code may run fine. By the way, you may need to link in the math library to make this code run, so does it check out? The final line shows two to the 1.0 power, yet back in the code, the loop stipulates the limit on variable x as less than 1.0. That's because floating point values are represented by binary converted decimal, and a precision error occurs in the loop. It repeats one extra time. Very small and very large looping values may also result in this type of unpredictable behavior. The solution is to use integers as looping values as…

Contents