Products > Programming

the asterisc in C

(1/3) > >>

Simon:
I am now aware that * can mean multiplication or pointer. So how are the two functions distiguised? is it the space in the multiplication?

A+B works but would A*B work or would that be interpreted as "B" being a pointer? So it should be written as A * B?

T3sl4co1l:
Whitespace is stripped so "A*B" is all that matters.

Dereference is a unary operation, so "A dereference B" is meaningless.  Therefore multiplication is unambiguously chosen.

You could however have "A**B" which would parse as "A*(*B)" or "A times (dereference B)".

Dereference can also be an LVALUE, i.e.,
*B = 1;
is a valid statement, but
A*B = 1;
is an error: the result of multiplication can only be an RVALUE (the expression returns a number).

As for the other form, direct pointer arithmetic is discouraged -- though perfectly syntactically valid.  The preferred alternative is array access, "B[A]", which is equivalent to *(B+A*sizeof(B[0])).

Likewise, unary "&" is the reference-of operator, while binary "&" is bitwise-and (and "&&" is logical-and). :)

Tim

NivagSwerdna:
de-reference has higher operator precedence than multiply in C.

https://en.cppreference.com/w/c/language/operator_precedence

Simon:
So:

#define SL_PORT_REGISTER(port, sl_register) *(uint32_t *)(SL_PORTS + (port*SL_PORT) + sl_register)

The port*SL_PORT multiplication would not become misinterpreted?

T3sl4co1l:
Right, though the leading asterisk could be misinterpreted:

A SL_PORT_REGISTER(port, sl_register)

would be parsed as A times the expression the macro expands to.  I guess the first * should be in parentheses?  Or is it really needed because it's already cast to a pointer type?  (Is it a double pointer type?  I've always been easily confused by pointer types...)

Tim