-4

I am writing a C program to generate Fibonacci numbers until 255 (as 8-bit values) using pic16f887. I try to check the carry bit from STATUS which is bit 0 (LSB) (I checked the datasheet), but all the time is 0.

#include <htc.h> 
#define N 20 
unsigned char i@0x20; 
unsigned char v[N]@0x30; 

void main(void)
{
    v[0] = 0;
    v[1] = 1;
    i = 2;
    while(1)    
    {
        v[i] = v[i-1] + v[i-2];

        if(STATUS &0b00000001) 
            goto end;
        i++;
    }
end:
    asm("NOP");
}

enter image description here

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

1 Answers1

3

There's no ordering between the (presumably volatile) register read and the arithmetic and load/stores in the loop. You can't "read the carry flag" from C because there is no way of positioning the flag read relative to the underlying arithmetic operations, even if you assume a machine that has a carry flag. Instead you need to write the explicit logic for carry and hope the compiler can recognize it and make use of the carry flag if that's the most efficient way to do it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 1
    Or you need to do the addition in asm as well, producing integer and flag output from the same `asm("..." : "=r"(int_out), "=r" (carry_out) : "r" (in1), "r"(in2));` statement. GCC6 and later supports syntax to have flag-condition outputs in the FLAGS register, at least on x86 and ARM: https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html – Peter Cordes Dec 20 '20 at 19:54
  • @PeterCordes: Yes that would work too, but the flags output doesn't work on OP's target. You'd need to have the asm move the carry flag to something expressible as output. – R.. GitHub STOP HELPING ICE Dec 20 '20 at 20:06
  • 1
    Right, that's why I used two `"=r"` outputs in my example asm statement. I guess the syntax isn't general, and has to be specially implemented for each target that wants it. – Peter Cordes Dec 20 '20 at 20:07