Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const in C function declaration and implementation

I have a function declared in code.h and implemented in code.c. it goes like:

void someFunc(const char*);

and

#include "code.h"
void someFunc(const char* str){ printf("%s\n", str); }

Now I found out I can remove the const in any one of the files (leaving it there in the other) and it compiles & runs with no errors. I wonder what's the meaning of this? Is one of the files the only one that matters?

It might sound like just an unimportant niche behaviour, but this fact means that a missed const can go unnoticed.

like image 727
Oded Sayar Avatar asked Apr 25 '26 10:04

Oded Sayar


1 Answers

What happens if declaration and definition of a function don't agree on whether an argument is const or not?

You should get a compilation error.

What to do?

Update your compiler.


With gcc 4.2.1, I am receiving an error, if I remove const from either the header or the source file:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c code.c
code.c:3:6: error: conflicting types for 'someFunc'
void someFunc(const char* str){ printf("%s\n", str); }
     ^
./code.h:1:6: note: previous declaration is here
void someFunc(char*);
     ^
1 error generated.

With gcc version 4.9.2 (Debian 4.9.2-10), I am getting the same behavior.

Same behavior with gcc's 7.1.0 version, online in Wandbox:enter image description here

My guess is that the behavior your are experiencing is architecture/compiler's version dependent.

like image 109
gsamaras Avatar answered Apr 26 '26 22:04

gsamaras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!