On 2024-07-11 23:36:22, Saurav Pal wrote:
> Hi all,
> 
> Suppose I have a pointer that I want to pass through function parameters.
> In the function, neither is the pointer reassigned, nor is the thing it
> points to modified in any form.
> 
> So, I would assume its function argument signature to be like FAR const
> struct my_struct * const ptr (The second "const" is my focus here).
> Similarly for things like const uint8_t my_num, etc. as well.
> 
> However, I have not really seen much use of specifying constants using
> const (in the way I have mentioned above). Most of the examples I see are
> of FAR const struct my_struct * ptr. I have heard the compiler can make
> better optimizations for const, and because of this, I try to spam const
> anywhere and everywhere I can. But I don't see too many such usages across
> the codebase, so I was wondering why that is (or I just maybe reading the
> code wrong, in which case, forgive me 🙏).
Because it doesn't really make much sense to do so. *EVERYTHING* in C is
passed as copy. Yes. Even pointers. Consider this

| void foo(const void * const ptr);
| ...
| const void *mem = 0x123;
| foo(mem);

It means that you won't change the memory at address 0x123. It's clear.
But second const actually only affects the function body itself. Even
without "const ptr", you won't be able to change users "mem" variable.
Even if you modify "ptr" inside "foo" you have only modified your local
ptr variable - same way as if you declared variable in body.

So it adds basically nothing. And ptr in fact IS NOT constant, it's just
an integer (simplifying) on functions call stack. It belongs to you.
Second const just bloats declaration and gives almost nothing in return.
First const is very important, you know to expect function modifying (or not)
what is rightfully yours. And those consts are promises anyway. Nothing
stops me from modifying your const if I wanted to (well... maybe except
for some hardware exception if data is really on RO medium ;)).

And compiler can easily determine if something is const or not without
the const keyword.

| int foo = 6;
| return foo * 4;

Will be reduced to "24" anyway, even without "const int foo".

-- 
.-----------------.-------------------.----------------------.-----------------.
| Michal Lyszczek | Embedded C, Linux |   Company Address    |  .-. opensource |
| +48 727 564 419 | Software Engineer | Akacjowa 10a; 55-330 |  oo|  supporter |
| https://bofc.pl `----.--------------: Brzezinka Sredzka PL | /`'\      &     |
| GPG FF1EBFE7E3A974B1 | Bits of Code | NIP:   813 349 58 78 |(\_;/) programer |
`----------------------^--------------^----------------------^-----------------'

Attachment: signature.asc
Description: PGP signature

Reply via email to