Pregunta

The following code works fine on CodeBlocks compiler but on MPLAB C18 compiler I don't get the same results. I am using PIC18 microcontroller.

Code

    int d[6];
    int all;

    d[0] = 6;
    d[1] = 4;
    d[2] = 8;
    d[3] = 0;
    d[4] = 0;

    all =  10000*d[0] + 1000*d[1] + 100*d[2] + 10*d[3] +  d[4];
    printf("%d", all);

Output on CodeBlocks: 64800

Output on MPLAB: -816

What is exactly the problem? Shouldn't this code work fine? Thanks!

¿Fue útil?

Solución

Objects that have the type int aren't guaranteed to be able to store values beyond -32767 or 32767. Your Code::Blocks implementation happens to extend this range, but your MPLAB C18 implementation (which isn't really a valid C implementation, by the way) doesn't. What you're seeing in your MPLAB implementation is undefined behaviour due to signed integer overflow. Use an unsigned type, and/or a wider type, such as long or long long. Don't forget to modify your printf format specifier accordingly. %u for unsigned int, %ld for long, %lu for unsigned long, %lld for long long, etc...

Otros consejos

according to this link , Your MCU is 8-bits system. so the length of the integer of your system is 16 bits. when you simulate your code with CodeBlocks, you are running your code with a 32-bits system ( or 64-bits system ) and the size of integer is 32 bits. so you will not get the same results. because in your MPLAP system you are overflowing the integer size

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top