0

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

  • 1
    You haven’t put a value for M_PI. See also https://stackoverflow.com/questions/6563810/m-pi-works-with-math-h-but-not-with-cmath-in-visual-studio . Without a value for M_PI, your area assignment simply becomes ‘area = * radius * radius’. Hence the error. – racraman Apr 08 '19 at 07:41
  • which compiler are you using? – P.W Apr 08 '19 at 07:41
  • Some standard libraries define their own `M_PI` when is included. I'd highly recommend picking a different name or else you're asking for a collision and undefined behaviour. – chris Apr 08 '19 at 07:45
  • 1
    @chris how is a colliding `M_PI` preprocessor symbol supposed to cause undefined behviour? – 463035818_is_not_an_ai Apr 08 '19 at 07:49
  • @P.W I'm using Code :: Blocks – Jonathan Goh Apr 08 '19 at 08:05
  • @JonathanGoh: Code::Blocks is an IDE. Asked for compiler because, the answer will depend on that as you can already see. – P.W Apr 08 '19 at 08:06
  • @P.W Sorry, just recalled it's the GNU GCC Compiler – Jonathan Goh Apr 08 '19 at 08:12
  • 1
    @user463035818, I misremembered. Yes, you'll get a compiler error, which isn't ideal over having the program be portable, but better than UB. (I believe I was mixing it up with multiple [ODR-related](http://eel.is/c++draft/basic.def.odr#12) definitions.) – chris Apr 08 '19 at 08:23

3 Answers3

3
#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 *.

john
  • 85,011
  • 4
  • 57
  • 81
2

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

Jaime
  • 5,770
  • 4
  • 23
  • 50
  • +1 best answer as no one should redefine pi. though it is quite upsetting that it doesn't work in Visual Studio. – Stack Danny Apr 08 '19 at 07:51
1

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.

CiaPan
  • 9,381
  • 2
  • 21
  • 35