for cicle problem

General discussion on mikroC PRO for PIC32.
Post Reply
Author
Message
relinquished
Posts: 222
Joined: 09 Apr 2011 11:08
Location: ITALY / NAPOLI

for cicle problem

#1 Post by relinquished » 20 Sep 2019 09:05

Hi, I'm using mikroc for the first time, I'm using a for loop to access bits of a variable.
thus it creates an infinite loop
void sct80(long dat){
char c;
for (c = 23; c >= 0 ; c--){
if ((dat >> c)& 0x01) {
so the cycle works but my code goes backwards
void sct80(long dat){
char c;
for (c = 0; c >= 23 ; c++){
if ((dat >> c)& 0x01) {
the problem is that if I use a positive increment the cycle works but I need the for loop to count down from 23 to 0, and if I do so the for loop creates an infinite loop.

samolet4e
Posts: 14
Joined: 16 Aug 2014 10:45

Re: for cicle problem

#2 Post by samolet4e » 24 Sep 2019 17:09

With regards to the for loop, it seems OK to me. The for statement does not create an infinite loop. Check if the block of statements below is enclosed within brackets.
Attachments
forLoopBackwards.png
forLoopBackwards.png (104.08 KiB) Viewed 1218 times

oliverb
Posts: 570
Joined: 24 May 2007 15:09

Re: for cicle problem

#3 Post by oliverb » 25 Sep 2019 09:55

You appear to be using "char" as the type for the counter. This is probably creating an unsigned char which would never go below zero because it would wrap round to 255, so the test ">= 0" would always return true.

You could try specifying "signed char", I believe that is a valid type. Then again if you are in a 32 bit environment then you should probably use "int" for counters?

User avatar
jovana.medakovic
mikroElektronika team
Posts: 986
Joined: 18 Dec 2018 10:36

Re: for cicle problem

#4 Post by jovana.medakovic » 26 Sep 2019 11:32

Hello,

@oliverb
Thank you, you are right.

In our help file, you can find a range of each of type which our compilers support.

Kind regards,
Jovana

Post Reply

Return to “mikroC PRO for PIC32 General”