douyu
douyu

Reputation: 2599

How understand ++ cast expression in cpp?

My understanding of the grammar ++ cast-expression is as follows:

float p = 3.14;
++(int)p;

But when I compile it with clang, it fails to compile. So how do understand ++ cast-expression and what is use for? (int)p is a cast-expression so why doesn't it work?

cpp-std-draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf

Upvotes: 0

Views: 194

Answers (1)

sepp2k
sepp2k

Reputation: 370102

++(int)p fails to compile because (int)p is not an l-value. However, that's a semantic error, not a syntactic one. Syntactically it's valid and matches the ++ cast-expression production.

An instance where ++ followed by a cast would be both syntactically and semantically valid would be when you cast to a reference (references being l-values). An example (albeit not a useful one) would be:

int x = 42;
++(int&)x;

In practice the cast-expression in ++ cast-expression will rarely be an actual cast. In most cases, cast-expression will be further reduced to primary-expression, allowing you to match expressions like ++x.

Upvotes: 5

Related Questions