Reputation: 25
In this basic C++ program why can't you print out the constant Pi?
#include <iostream>
using namespace std;
#define Pi 3.1415;
int main() {
cout << Pi << endl;
return 0;
} //main
Upvotes: 0
Views: 165
Reputation: 1
Your Pi
definition is a macro not a constant and it expands to a superfluous ;
in your output statement
#define Pi 3.1415; // <<
will become
cout << 3.1415; << endl;
// ^
and you end up with a compilation error.
To declare a constant correctly in C++, you should write
const double Pi = 3.1415;
Upvotes: 1
Reputation: 4023
You need to remove ;
after 3.1415
.
The code
#define Pi 3.1415;
implies that whenever you use Pi
, it will be replaced by 3.1415;
. Notice how the semicolon also gets included along with the double. So when you use cout<<Pi<<endl
, the compiler reads it as cout<<3.1415;<<endl
, which you can see will give an error.
Upvotes: 1
Reputation: 4536
Your Pi
definition contains a semi-colon, ;
.
Upon substitution, the compiled code is
cout << 3.1415; << endl;
When it should be
cout << 3.1415 << endl;
In other words, do
#define Pi 3.1415
Without the semi colon.
Though, better still is to not use #define
for things like this.
See for example How to use the PI constant in C++ for suggestions.
Upvotes: 5