Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is typecasting a unary operation?

Tags:

c

In C, is typecasting a variable/value considered a unary operation?

And to add to this is typecasting an integer value (perhaps before you apply a mask to it) also a unary operation? Let's say I have

((uint64_t)1 << 30 & 0xFFFF0000FFFF0000LL)

Is 1 padded with zeros (up to 64 bits) and then shifted over?

like image 989
OfLettersAndNumbers Avatar asked Jan 27 '26 17:01

OfLettersAndNumbers


1 Answers

Logically, yes, it's reasonable to think of it as a unary operator since it takes one operand.

But if you look at the way the C standard classifies expressions, unary operators are covered in section 6.5.3, and the cast operator is described separately in section 6.5.4.

There actually is at least one case where the distinction matters.

sizeof unary-expresson

is one of the several forms of unary-expression. If a cast operator (type-name) were treated as a unary operator like the others, then this:

sizeof (int) 42

would be a valid unary expression: 42 would be the operand of the cast operator, which in turn would be the operand of the sizeof unary operator. But in fact it's a syntax error (because sizeof (int) by itself is a valid expression). To avoid that problem, unary operators and the cast operator are defined separately (in effect given different precedences). To write the above while avoiding a syntax error, you need to add parentheses:

sizeof ((int) 42)

Reference: N1570, the latest freely available draft of the 2011 ISO C standard.

like image 121
Keith Thompson Avatar answered Jan 29 '26 10:01

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!