The following is a foo function that take a constant pointer: void foo(int *const x); If you point x to another adress inside foo function, it will not compiled. The author seems think that void foo(cont int *x); is function that takes a constant pointer which is wrong, it is a function that takes pointer to constant object. In this case, it is legal if you point x to another address in memory inside foo function.
Const and Optimization in C
41–44 of 44 posts
Re: Const and Optimization in C
#42Here is the gist of the explanation from the article: And there aren’t any rules against casting away const to modify an object that isn’t itself const. This means the above (mis)behavior of foo isn’t undefined behavior for this call. Notice how the undefined-ness of foo depends on how it was called. Wtf? This seems like a huge potential optimization gain missed. Surely by know it can't just be enabled because a lot…
Re: Const and Optimization in C
#43Earlier quoted context omitted.
[Saw a response here, but it disappeared before my reply. Posted here anyway in case it clarifies my first paragraph.] Did you check out the link? https://godbolt.org/g/aaC4B7 My surprise is that none of clang, gcc, or icc give any warning on this with -Wall -Wextra: 1 void copy_const(const int * const arg) { 2 int *copy = (int *)arg; 3 (*copy)++; 4 } I agree that the cast on line 2 is legal and requires no warning.…
In gcc try -Wcast-qual
That said, it looks like -Wcast-qual is also supported by clang and icc. Clang includes it in "-Weverything", which gcc and icc do not support. Even if not ideal for this issue, I'm sure there are cases where it would help to catch bugs.
Re: Const and Optimization in C
#44Earlier quoted context omitted.
What is the argument in favor of specifically allowing casting away const of pointers?
The strongest argument is to support a sort of poor man's const-generics. Consider a function like strchr(). This locates a character in a (const) string, and returns a (non-const) pointer to it. The idea is that you can use this on both const and non-const strings. Call it on a const string, you get back a non-const pointer (which you better treat as const!) But call it on a non-const string, you get back a non-cons…