Reputation: 639
Check this out:
#include <iostream> //input outut like cout, cin
#include <string> //strings
#include <cstdlib> //includes random num generators and basic c++ functions
#include <limits> //functions for min and max for data types
#include <vector>
#include <numeric> //sequences of values
#include <cmath> //math functions
#include <sstream> //string stream
#include <ctime> //time
#include <algorithm> //includes sort
#include <fstream> //alllows ofstream and ifstream for some reason? unicode vs ansi?
#include "Shape.h"
#include "Circle.h"
#include <functional> //allows you to use function poitner? <function>
#define PI 3.14159 //anywhere you see PI, it will be replaced with the number to its right
#define AREA_CIRC (radius) (PI * pow(radius, 2))
int main(){
cout << "Circle Area " << AREA_CIRC(5) << endl;
}
Whenever I run this code, it gives me this error:
Error C2065 'radius': undeclared identifier Derektut
Why? declaring int radius in the macro definition makes no difference
Upvotes: 3
Views: 1803
Reputation:
The below was mostly written before you made your edit, so I will suggest removing the space between AREA_CIRC
and (radius)
and see if that helps (it worked for me).
Worth noting that the rest still mostly applies, except maybe the part which suggested getting rid of the type declaration.
Macros don't use type declarations. They are pure text substitutions (which makes them somewhat unsafe to use). Thus, int
here is unnecessary:
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14159 //anywhere you see PI, it will be replaced with the number to its right
#define AREA_CIRC(radius) (PI * pow(radius, 2))
int main(){
cout << "Circle Area " << AREA_CIRC(5) << endl;
}
That should work, though especially if you're using macros, I don't recommend using namespace std even though I've used it here quickly to create an example.
Ultimately, it'd be better to use a constexpr
function instead:
constexpr float AREA_CIRC (int radius) { // double will work here as well, if desired
return (PI * pow(radius, 2));
}
Also, excellent suggestion by @passing_through, you can also change PI
to a constexpr
as well:
constexpr double PI = 3.14159;
Upvotes: 2
Reputation:
Your macro expands as
cout << "Circle Area " << (radius) (PI * pow(radius, 2))(5) << endl;
not the way you expected. @passing_through gave you the cure.
Upvotes: 2
Reputation: 1931
#define AREA_CIRC (radius) (PI * pow(radius, 2))
means
replace all
AREA_CIRC
with(radius) (PI * pow(radius, 2))
As a result, you just get plain text substitution including radius
which really is an unknown identifier. What you probably meant was a function-like macro:
#define AREA_CIRC(radius) (PI * pow(radius, 2))
Just remove the space between the macro name and its opening bracket.
Upvotes: 8