Thread: Not less than if stament expression

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    29

    Not less than if stament expression

    Hi,

    I have an array with 8 elements and I want to print the lower 4 elements with for 8 loops and the index starts from 3, so it prints element[3], element[2] element[1], element[0], and the rest to zeros but I want when the index reaches 0 and starts to print from index 3 again, how to do that? I tried this code but didn't work, it prints until the last element but the rest are zeros. I want a to be initialized with 3 again. If I tried a==0, it prints 3 elements and skips element[0].


    Code:
    uint8_t ascend[8]={0x09, 0xc0, 0x20, 0x1f, 0x1f, 0x20, 0xc0, 0x00}; 
       uint8_t i,a=3,cnt=8; 
    
    int main(void) { 
    
         for (i=0;i<cnt;i++) 
         { 
    printf("data 0x%.2x\n",ascend[a--]); 
    if (a<0)a=3; 
         } 
         return 0; 
     }
    Last edited by wolfrose; 01-17-2018 at 10:54 AM.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    627
    Code:
    a.c: In function ‘main’:
    a.c:9:15: warning: comparison is always false due to limited range of data type [-Wtype-limits]
             if (a < 0) a = 3;
                   ^
    Since a is unsigned, it will never be less than 0. It will instead wrap around to its highest value. Try this:
    Code:
        for (i = 0; i < cnt; i++) {
            printf("data 0x%.2x\n", ascend[a]);
            if (a-- == 0) a = 3;
        }
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  3. #3
    Registered User
    Join Date
    Jan 2016
    Posts
    29
    It worked! WOW, I'm really impressed how just changing the location of decrement changes the whole process! Thanks but why that happened?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. expression
    By Amit Choubey in forum C Programming
    Replies: 4
    Last Post: 12-20-2012, 02:23 AM
  2. If else if stament help
    By langamer101 in forum C Programming
    Replies: 30
    Last Post: 01-18-2012, 07:16 PM
  3. what is the value of this expression?
    By theju112 in forum C Programming
    Replies: 16
    Last Post: 08-12-2011, 12:29 PM
  4. initializer expression list treated as compound expression
    By karthikeyanvisu in forum C Programming
    Replies: 7
    Last Post: 02-26-2011, 05:19 PM
  5. Replies: 2
    Last Post: 11-25-2009, 07:38 AM

Tags for this Thread