karaxuna
karaxuna

Reputation: 26940

Illegal indirection when multiplicating

I'm starting to learn C++. Here is a problem that I have:

#include <iostream>
using namespace std;
#define PI 3.14;

int main(){
    double r = 5.0;
    double circle;
    double inp;

    circle = 2 * PI * r;
    cout << circle;
    cin >> inp;
}

It shows error: error C2100: illegal indirection. I've googled but found no answer. Thanks

Upvotes: 3

Views: 310

Answers (2)

paxdiablo
paxdiablo

Reputation: 882386

Macros are (relatively) simple substitutions so, when you write:

#define PI 3.14;
circle = 2 * PI * r;

it actually ends up as:

circle = 2 * 3.14; * r;

effectively the two statements:

circle = 2 * 3.14;
* r;

That last line would be a perfectly valid expression (albeit it not a very useful one) if r were a pointer of some description. However, given it's a double, that's where you're getting the illegal indirection from.

The use of macros is something you should generally avoid nowadays except in very specific circumstances. The use of them to provide inline functions has been subsumed mostly by the inline keyword ("mostly", because the inline keyword is only a suggestion).

In addition, using it to provide constants can be better done (with the advantage of full type support and usually better debugging) with the const keyword.

In other words, your PI constant would be better written as something like:

const double PI = 3.141592653589;

Just about the only place I use the pre-processor nowadays is for conditional compilation.


As an aside, you probably meant circumference rather than circle. The former is the length around the outside of the circle, the latter isn't really a length value at all.

Upvotes: 6

RichardPlunkett
RichardPlunkett

Reputation: 2988

#define PI 3.14;

The ; is wrong, delete it.

btw, your line expands to circle = 2 * 3.14; * r; So the compiler is then complaining about the *r, which explains the error message.

Upvotes: 11

Related Questions