3 ms·
[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://god
by nkurz 10y ago
[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 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. My surprise is that there is no warning for the write on line 3, since I think this is undefined behavior according the quoted part of the spec. Isn't this trying "to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type"?
I realize that the compiler has no obligation to issue a warning here, and in fact is fully entitled to my first-born as soon as it encounters undefined behavior. Still, it seems like it would be a useful place to offer the user a warning just as it does in the case of direct modification:
1 void write_const(const int * const arg) {
2 (*arg)++;
3 }
clang: "error: read-only variable is not assignable"
gcc: "error: increment of read-only location '*arg'"
icc: "error #137: expression must be a modifiable lvalue"
- Too 10y agoIn gcc try -Wcast-qual
- nkurz 10y agoIt'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.