Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make the meaning of /* for dereference and dividing not for commenting by adding some special character

Tags:

c++

c

I have a code like this:

int quotient = 100/*ptr; 

where ptr is a pointer to interger.

But it's taking /* as the comment.
How can I make the meaning of divide by pointer dereference value? What extra special character I have to put to have this meaning?

like image 245
InQusitive Avatar asked Jan 02 '15 11:01

InQusitive


People also ask

What's the meaning of dereference?

(programming) To access the value or object located in a memory location stored in a pointer or another value interpreted as such; to access a value being referenced by something else.

What is the difference between address (&) and dereference (*) operator?

We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable. The dereference operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var.

What is dereference operator in C++ with example?

The . * operator is used to dereference pointers to class members. The first operand must be of class type. If the type of the first operand is class type T , or is a class that has been derived from class type T , the second operand must be a pointer to a member of a class type T .

What is pointer referencing and dereferencing?

As illustrated, a variable (such as number ) directly references a value, whereas a pointer indirectly references a value through the memory address it stores. Referencing a value indirectly via a pointer is called indirection or dereferencing.


2 Answers

This happens because language tried to reuse the tokens. (* in this case)

Solution is to put a space between / and * to beat maximal munch.

int quotient = 100 / *ptr;

Another way is to add a parenthesis or use another local variable:

int quotient = 100/(*ptr);
like image 126
Mohit Jain Avatar answered Sep 28 '22 20:09

Mohit Jain


First, you can replace *ptr with ptr[0], as both have the same semantics:

int quotient = 100/ptr[0];

And since array indexing is commutative, you can swap the operands:

int quotient = 100/0[ptr];

To the casual reader, this may look like division by zero, but of course [] has higher precedence than /. You may want to put a space there, just in case:

int quotient = 100/0 [ptr];

Congratulations, you now have a job for life!

like image 25
fredoverflow Avatar answered Sep 28 '22 20:09

fredoverflow