user123
user123

Reputation: 25

Constants in Basic C++ program

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

Answers (4)

ashwini
ashwini

Reputation: 142

Remove the semicolon from macro definition

#define PI=3.142

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

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

Ayushi Jha
Ayushi Jha

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

swalog
swalog

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

Related Questions