最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c - is using the + operator a way to remove qualifiers within the typeof operator instead of using typeof_unqual in C23? - Stack

programmeradmin7浏览0评论

C23 added the typeof_unqual keyword as a way to get the unqualified type of an object. Can't you just use the + operator on scalar types to avoid this? (I know this doesn't work on struct/union typed objects). I get different results on different compilers with this.

int main() {
    const int A;
    typeof(+A) B;
    B = 5;
    return 0;
}

C23 added the typeof_unqual keyword as a way to get the unqualified type of an object. Can't you just use the + operator on scalar types to avoid this? (I know this doesn't work on struct/union typed objects). I get different results on different compilers with this.

int main() {
    const int A;
    typeof(+A) B;
    B = 5;
    return 0;
}
Share Improve this question edited Mar 27 at 12:12 Badasahog asked Mar 27 at 10:09 BadasahogBadasahog 8714 silver badges20 bronze badges 6
  • 3 Pleased provide more detail on "I get different results on different compilers with this." – chux Commented Mar 27 at 10:13
  • The unary + wouldn't work on pointer type objects, but you could use the binary typeof(0+(A)) on those, and on other scalar types. (Or you could use typeof(&*(A)) for pointer type objects.) – Ian Abbott Commented Mar 27 at 10:20
  • @chux works on gcc, breaks on msvc. default settings, language set to c23/clatest – Badasahog Commented Mar 27 at 11:07
  • Does MSVC even support C23 though? Through which options? By default, it doesn't even conform to C99. – Lundin Commented Mar 27 at 12:46
  • 1 @Badasahog "works on gcc" --> did you test with types like short that are narrower than int? – chux Commented Mar 27 at 13:44
 |  Show 1 more comment

1 Answer 1

Reset to default 5

Can't you just use the + operator on scalar types to avoid this [for arithmetic types]?

Yes, except the integer promotions will be applied. C 2024 6.3.3.1 specifies that lvalue conversion (use of an lvalue in an expression for its value) removes qualifiers: “If the lvalue has qualified type, the value has the unqualified version of the type of the lvalue…”

An alternative that does not apply the integer promotions is typeof(0, A). This can also be used on non-arithmetic types.

I get different results on different compilers with this. [From a comment:] breaks on msvc.

Testing on Compiler Explorer shows MSVC 19.40 retains the const qualifier in typeof(+A). MSVC does not conform to the C standard in this regard.

Further experimentation shows you can work around this with typeof(A+0). With typeof(0+A) or typeof(x+a), where x was declared int, MSVC still produced a qualified type, but making A the left operand of + produces an unqualified type.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论