MISRA Discussion Forums
for loop iterator being comapred to a variable of another type - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.14 Control statement expressions (https://forum.misra.org.uk/forumdisplay.php?fid=169)
+---- Thread: for loop iterator being comapred to a variable of another type (/showthread.php?tid=1583)



for loop iterator being comapred to a variable of another type - ZESS - 11-10-2021

So I had this bug where I was trying to compare my "for loop" iterator to a variable "var":
Code:
for (u_int8_t i=0; i<var; i++) ....


"var" was coded on 16 bits while "i" was coded on 8 bits , this led to an infinite loop as "i" could never reach "var".
I was wondering why this was not raised as a MISRA warning while compilation phase, I thought at first that I was disabling some rules but turned out I was not. I looked for a MISRA rule prohibiting this kind of implementation, but I could not find any.

I'm not sure if it's related to the tool I'm using or indeed there is no such rule that prevents comparing two variables with two different data types especially if they are used as break condition to loops.


RE: for loop iterator being comapred to a variable of another type - misra-c - 27-11-2021

Whether the code is an infinite loop will depend on the value of "var".  If it is less than 255 there is no problem.  If examination of the code shows that "var" may exceed 255 then rule 14.3 would be violated since the controlling expression will always be false.


RE: for loop iterator being comapred to a variable of another type - ZESS - 14-12-2021

(27-11-2021, 09:10 AM)misra-c Wrote: Whether the code is an infinite loop will depend on the value of "var".  If it is less than 255 there is no problem.  If examination of the code shows that "var" may exceed 255 then rule 14.3 would be violated since the controlling expression will always be false.

Thanks for the reply, does this mean that the following code does not violate rule 14.3 : 
Code:
u_int32_t var = var2; // var2 being u_int32_t as well
for (u_int8_t i=0; i<var; i++) ....
as it is not clear whether var/var2 exceeds 255 or not ?


RE: for loop iterator being comapred to a variable of another type - misra-c - 13-02-2022

Whether the code is an infinite loop will depend on the value of "var2".  If it is less than 255 there is no problem.  If examination of the code shows that "var2" and hence "var" may exceed 255 then rule 14.3 would be violated since the controlling expression will always be false.

The type of var and var2 are irrelevant. It will depends on the range of values that are held.