for-looppicunsigned-char

Unsigned char out of range


I am trying to figure out, how to use an unsigned char type of a variable inside a for loop, while not "breaking" out of range for unsigned char, which can vary form 0 to 255.

    main(void) {
        TRISC = 0;
        LATC = 0;
        unsigned char j;
    
        for (j = 0; j <= 255 ; j++){
            LATC = j;
            __delay_ms(1000);
        }
        return;
    }

This is code in C, where PIC is programmed. "TRISC = 0" means setting port C as an output and "LATC" is referring to port C itself. Basically I want to assign values from including 0 to 255 to this port. But if I try to compile this, the compiler (xc8) returns following two warnings:

enter image description here

enter image description here

I cannot quite understand what these two are saying, but I assume it has to do something with variable j exceeding the limit value of unsigned char, that is 255 (in last iteration j = 256, which is not allowed/defined). However, this code gets compiled and works as meant. But I still want to write and understand a code that assigns port C the value of 255 without entering "prohibited" range of values.

*P.S. I would use any other variable type than unsigned char or char, however to ports in PICs only these two types can be applied directly (without conversion).


Solution

  • j <= 255 is always true if j is only 8 Bit wide.

    This version should work:

    main(void) {
        TRISC = 0;
        LATC = 0;
        int j;
    
        for (j = 0; j <= 255 ; j++){
            LATC = (unsigned char)j;
            __delay_ms(1000);
        }
        return;
    }