'square' was not declared in this scope??

/*I'm learning C++ through the use of Stroustrup's Programming: Principles and Practice Using C++. I've ran into a few problems that have me wondering whether typos are to blame or if my xcode libraries need to be updated or if some other issue is to blame.
There are two similar sets of code below. The first produces the error: "'square' was not declared in this scope" on line 9. The second produces no problems and executes just fine. What gives?

If an update is what's needed, how would I go about doing that? Thank you.*/

#include <iostream>
#include<cmath>
using namespace std;

int main ()
{
for (int i=0; i<100; ++i)
{
cout <<i<<" "<<square(i)<<endl; //'square' was not declared in this scope
}
return 0;
}

/*Versus: This code which elicits a (correct) result:*/

#include <iostream>
#include<cmath>
using namespace std;

int main ()
{
for (int i=0; i<100; ++i)
{
cout <<i<<" "<<i*i<<endl;
}
return 0;
}
Last edited on
In the first you're trying to call a function named square(), and neither I nor your compiler can find a declaration of that function.
http://www.cplusplus.com/reference/clibrary/cmath/

Use that reference for the math.h functions. I believe you're looking for pow()

Edit: And please use the [code][/code] tags, it makes it very hard to read code otherwise. Thank you.
Last edited on
closed account (zb0S216C)
When the compiler says an identifier isn't within scope, it means it doesn't know what the identifier is; it's never seen it before; you've never told it what it is.

To fix this, you'll need to declare square(). However, it seems you want the function to compute the square root. For that, you'll need sqrt().

Wazzak
Framework wrote:
To fix this, you'll need to declare square(). However, it seems you want the function to compute the square root. For that, you'll need sqrt().


I think they're actually looking for a function to "square" i. The pow() function should suffice.
Awesome. The pow() function worked like butter.
Thanks Zhuge, Volatile Pulse, and Framework.
You shouldn't bother with using pow for this kind of simple calculation. Just use i*i. pow is for weird stuff like 2-0.37
@firedraco
I completely agree with you, but since he had it in his second program, I figured he wanted a function.

@cvivious
This might be a chance for you to write your own "square" function. Just a thought.
Topic archived. No new replies allowed.