Add PWR080: Conditionally initialized variables can lead to undefined behavior - #103
Conversation
1ecf3d3 to
4760960
Compare
| pure function transform_and_sum_improved_f(n, array, option) bind(c) | ||
| use iso_c_binding, only: c_double, c_int | ||
| implicit none | ||
|
|
||
| integer(kind=c_int), intent(in), value :: n | ||
| real(kind=c_double), dimension(n), intent(in) :: array | ||
| integer(kind=c_int), intent(in), value :: option | ||
| real(kind=c_double) :: transform_and_sum_improved_f | ||
|
|
||
| real(kind=c_double) :: sum | ||
| real(kind=c_double) :: factor | ||
| integer(kind=c_int) :: i | ||
|
|
||
| sum = 0.0 | ||
|
|
||
| if (option == 1) then | ||
| factor = 1.0 | ||
| else if (option == 2) then | ||
| factor = 2.0 | ||
| else | ||
| ! Nullifies the computation | ||
| factor = 0.0 | ||
| end if | ||
|
|
||
| do i = 1, n | ||
| sum = sum + array(i) * factor | ||
| end do |
There was a problem hiding this comment.
I disagree this is a good example solution: PWR080 should be about the unitialized variable factor alone, it should not bother with another variable like option and worry if all it's possible values are properly checked, that is foreign to the real issue.
The simplest solution (and the one that would allow linting tools to produce autofixes for PWR080) would be to just initialize factor in it's declaration to avoid potential undefined behavior. Whether the value chosen is "correct" or not, is also besides the point, which is to turn undefined behavior into consistently defined behavior.
There was a problem hiding this comment.
I disagree this is a good example solution: PWR080 should be about the unitialized variable
factoralone, it should not bother with another variable likeoptionand worry if all it's possible values are properly checked, that is foreign to the real issue.
That's a good point of view! I've updated the solutions to suggest the default initialization of factor.
282e3c2 to
764d64a
Compare
764d64a to
629d868
Compare
Add entry and benchmark for a new check. My results: