Jonathan Goh
Jonathan Goh

Reputation: 1

invalid type argument of unary '*' (have double)

Just started learning c++ got this error:

C:\Users\KC\Documents\Math.cpp|9|error: invalid type argument of unary '*' (have 'double')|

This is the code:

#include <iostream>
#include <cmath>
#define M_PI
using namespace std;

int main()
{
   double area, radius = 1.5;
      area = M_PI * radius * radius;
   cout << area << "\n";
}

can someone explain to me what did I do wrong. Thanks

Upvotes: 0

Views: 1822

Answers (3)

CiaPan
CiaPan

Reputation: 9570

You used the preprocessor directive #define M_PI which defined M_PI as an empty string. So, after substitution of the empty contents for M_PI, the expression

area = M_PI * radius * radius

became

area = * radius * radius

and the first asterisk became an unary operator, with the whole expression interpreted as

area = (* radius) * radius

That unary asterisk can't reasonably work with a double argument, hence an error message.

Upvotes: 1

Jaime
Jaime

Reputation: 5975

I suggest to use:

#define _USE_MATH_DEFINES
#include <cmath>

and remove this line:

#define M_PI

More info in this answer: M_PI works with math.h but not with cmath in Visual Studio

Upvotes: 2

john
john

Reputation: 87997

#define M_PI

should be

#define M_PI 3.14159

(or whatever value you want to give for pi).

You defined M_PI as nothing, which means that this code

  area = M_PI * radius * radius;

becomes this code

  area = * radius * radius;

and your compiler is complaining about the unexpected *.

Upvotes: 4

Related Questions