pdel
pdel

Reputation: 705

How do I define a constant in C++?

For the code:

#define e 2.71828183;

double p ( int x )
{
    return 1 / ( 1 + pow ( e, -1.0 * x ) );
}

I get:

math.cpp: In function ‘double p(int)’:
math.cpp:11: error: expected ‘)’ before ‘;’ token
math.cpp:11: error: expected ‘)’ before ‘;’ token
math.cpp:11: error: expected primary-expression before ‘,’ token
math.cpp:11: error: expected ‘;’ before ‘)’ token

Upvotes: 2

Views: 959

Answers (3)

Alexander Poluektov
Alexander Poluektov

Reputation: 8063

As you question is about C++:

Here you can see problems of macro-substitution in action. Instead, use the constant:

double const e = 2.71828183;

Upvotes: 3

codaddict
codaddict

Reputation: 455460

There is a ; at the end of your macro replacement:

#define e 2.71828183;

On preprocessing your return statement will look like:

return 1 / ( 1 + pow ( 2.71828183;, -1.0 * x ) );
                                 ^^

which results in syntax error.

To fix this remove that ;

Upvotes: 12

DuckMaestro
DuckMaestro

Reputation: 15915

The macro shouldn't have a semi-colon.

Upvotes: 3

Related Questions