Reputation: 71
Is there any operator in c which is both unary and binary ? This question was asked in one of the interview.
Upvotes: 4
Views: 10068
Reputation: 106022
What I think only .
operator is both unary and binary in C (not specified in standard):
.
:- Unary: In designators of structures- {.meber1 = x, .member3 = z}
(C99 and latter). Binary: Accessing structure members.
There is no operator in C which is unary and binary as well.
Symbols, like +
, -
, *
and &
, are used as unary and binary operators but then these symbols are treated as different operators:
+
, -
Unary: i = -1
j = +1
. Binary: i = i+1
, j = j+1
*
Unary: Dereference operator. Binary: Multiplication operator. &
Unary: Reference operator. Binary: Bitwise AND
operator.Upvotes: 2
Reputation: 602
The asterisk (*) can be used for dereferencing (unary) or multiplication (binary).
The ampersand (&) can be used for referencing (unary) or bitwise AND (binary).
The plus/minus signs (+/-) can be used for identity/negation (unary) or addition/subtraction (binary).
But, as others pointed out, those are symbols shared by different operators. Each of those operators have only one n-arity.
Upvotes: 10
Reputation: 263307
No, there isn't. Every operator is either unary, binary, or ternary.
Some unary and binary operators happen to use the same symbol:
*
for dereference and multiplication-
for negation and subtraction+
for identity and addition&
for address-of and bitwise "and"But unary and binary *
are still distinct operators that happen to be spelled the same way.
Upvotes: 7