From the course: Secure Coding in C (2019)
Unlock the full course today
Join today to access over 24,800 courses taught by industry experts.
Looping with floating point values - C Tutorial
From the course: Secure Coding in C (2019)
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
Formatting preprocessor directives1m 23s
-
(Locked)
Using an assignment as a condition1m 31s
-
(Locked)
Avoiding putchar() in a while loop1m 35s
-
(Locked)
Using the system() call1m 58s
-
(Locked)
Accessing elements beyond the array size2m 2s
-
(Locked)
Converting integers2m 26s
-
(Locked)
Looping with floating point values1m 39s
-
(Locked)
Using return values1m 58s
-
(Locked)
Confirming when EOF has been read2m 31s
-
(Locked)
Challenge: Fix the code1m 12s
-
(Locked)
Solution: Fix the code2m 12s
-
-
-
-
-