Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C (also C++), how '&' operator works as both address operator and bitwise operator ? As operator overloading is not supported by C

The operator '&' can be used in both of following way int a; scanf("%d",&a); and printf("%d",1&2). But different behaviour (for first as address operator and second time as bit-wise operator). I know operator overloading is not there in C. Then how it works ?. Also highlight for c++.

like image 432
Rishi Avatar asked Oct 26 '25 07:10

Rishi


2 Answers

I know operator overloading is not there in C.

This is incorrect. a + b performs integer addition if a and b are integers, floating-point addition if a and b are floating-point numbers, and pointer arithmetic if a or b is a pointer.

C has operator overloading built into the language. It does not support custom operator overloading defined by the program.

In the case of & being an operator for taking an address and for performing a bitwise AND, the distinction is made by the language grammar. The & for taking an address can appear only applied to a cast-expression in the grammar. The & for bitwise AND can appear only after an AND-expression and before an equality-expression. These “tokens” (cast-expression, AND-expression, and equality-expression) may be unfamiliar to you, but they are formally defined in the grammar for the C language, and, as the compiler is parsing source code, it recognizes the structure of expressions and matches the source code to the tokens of the grammar. This is also true for C++ except for a minor technical difference: In C++, one of the tokens is and-expression instead of AND-expression.

The definition of the grammar is such that recognition of these tokens always uniquely distinguishes how the & operator is being used.

like image 103
Eric Postpischil Avatar answered Oct 28 '25 20:10

Eric Postpischil


In "C" language, operators have different meaning when they are used as prefix to expression, suffix to expression or "infix" (between two expressions).

Consider '*', which performs multiplication as 'infix' operator, and pointer indirection when used as a prefix. Similarily, the '-' operator, which performs subtraction as 'infix' operator, and negation when used as a prefix.

Basically, it's not about overriding, it if the operator appears between two expressions, or as a prefix to a single expression.

In the same way, The "C" compiler knows if the '&' is bit-wise and, or address-of, based on it's position is the expression: If it is between two expressions, it's the AND, if it is before an expression, it is 'address-of'.

See https://en.wikipedia.org/wiki/Infix_notation about infix.

like image 27
dash-o Avatar answered Oct 28 '25 21:10

dash-o



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!