Purpose of const argument other than avoiding mistake

76 views Asked by At

I'm programming 8051 microcontroller using keil C51 C compiler, which only support C90.

I want to send a byte of data via UART, the function look like this:

void Uart_send(char data){
   //...
}

Use 1:

char a = 123;
Uart_send(a); //work great

Use 2:

Uart_send(123);//doesn't work, but no error or warning from compiler

In the latter case, 1 byte is sent, but not the correct value (123).

If I change my code to:

void Uart_send(const char data){
   //...
}

Then everything works perfectly.

From my understanding and several sources on the internet, the only purpose of "const" is to prevent the function from changing its argument (in other words, to prevent the programmer from changing argument by mistake). Then why does my second method not work?

Edit: This is my full code:

UART.h

typedef struct {
    char Buffer[10];
    char *p;
    char Ready;
    void (*Load)(char Data);
    void (*Transmit)();
    void (*Flush)();
} _uart;
extern _uart UART;

UART.c

#include "UART.h"
#include <reg51.h>

#define EOF 0x00
/*
0000_0000: EOF
0000_0001: countdown
1xxx_xxxx: primary time set
1xxx_xxxx: secondary time set
0111_xxxx: set phase

*/
#define Wait() for(i = 0; i < 3; ++i)
void Load(const char Data){
    *UART.p = Data;
    if(Data == EOF){
        UART.Ready = 1;
    }
    ++UART.p;
}
void Transmit(){
    int i;
    char *p;
    p = UART.Buffer;
    while(1){
        SBUF = *p;
        while(~TI);
        TI = 0;
        Wait();//make sure slave finish process data before sending next byte
        if(*p == EOF) break;//we are done
        ++p;
    }
    UART.Flush();
}
void Flush(){
    UART.p = UART.Buffer;
    UART.Ready = 0;
}
_uart UART = {
    {EOF, EOF, EOF, EOF, EOF, EOF, EOF, EOF, EOF, EOF},
    UART.Buffer, 0,
    Load,
    Transmit,
    Flush
};

main.c

#include "UART.h"
//.....
UART.Load(123);
UART.Load(0x00); //0x00 = EOF
UART.Transmit();
2

There are 2 answers

1
Some programmer dude On

Now when we can see your code the problem is clear: You don't have a function declaration (a prototype) in the header file.

In C you really need to declare things before you can use them, otherwise the compiler will not know about them.

Note that there's a big difference between standard editions here. In older C standards (before C99) using a function would implicitly declare by deducing the argument types from the call (which in your case would have been wrong since 123 is an int). From C99 and onward that's not really allowed anymore.

0
pmg On

Purpose of const argument other than avoiding mistake

Compiler can do some optimizations with the const present.