Search code examples
c++coperator-overloadingbitwise-operatorsaddress-operator

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++.


Solution

  • 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.