Live data from Hacker News

Const and Optimization in C

nullprogram.com

41–44 of 44 posts

Re: Const and Optimization in C

#41
post #21

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.

Update: The author have been corrected the 2nd paragraph. My comment above is not valid anymore

Re: Const and Optimization in C

#42
post #40

Here 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…

Is there any portable way to tell the compiler it can do this kind of optimization in C ? Wouldn't that be useful ?

Re: Const and Optimization in C

#43
post #39
post #37

Earlier 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

It's good to know that it exists (and that it's not included in -Wall -Wextra) but it's not quite what I'm looking for. The cast itself is well defined --- it's the subsequent write that is the issue. While it wouldn't be possible to catch all of these, those that are caught are likely genuine bugs.

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

#44
post #13

Earlier 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…

And that's why D has the 'inout' qualifier
Post reply on HN