Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
for loop iterator being comapred to a variable of another type
#1
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.
Reply
#2
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.
Posted by and on behalf of the MISRA C Working Group
Reply
#3
(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 ?
Reply
#4
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.
Posted by and on behalf of the MISRA C Working Group
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)