0

While following this Youtube tutorial (see the relevant code below) I get the following error:

error line 6
error: expected constructor destructor or type conversion before'('

What might cause this error and how do I solve it?

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <time.h>
void myfun(int);//using own function
myfun(8);//pow(4.0,10.0)
using namespace std;
int main()
{
    double num1;
   srand(time(0));// to get a true random number
    double num2;
    num1 = pow(3.0, 9.0);//2 to the power of 4
    cout << num1 <<endl;
    num2 = rand() %100;//random number out of 100
    cout << "\nrandom number = " << num2 << endl ;

    return 0;
}
void myfun(int x)
{

    using namespace std;
    cout << "my favourite number is " << x << endl;
}
Bart
  • 19,692
  • 7
  • 68
  • 77
  • 5
    I'd recommend a [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) over a video tutorial any day. Do take care to make the code you give us compilable apart from your errors, too, without having to manually erase something off of every line, please. – chris Jul 26 '12 at 17:04

2 Answers2

4

This is a declaration:

void myfun(int);//using own function

This is a function call:

myfun(8);//pow(4.0,10.0)

You can't call a function outside of a context.

Try moving it inside main. What are you trying to achieve?

int main()
{
    myfun(8);  //<---- here

    double num1;
    srand(time(0));// to get a true random number
    double num2;
    num1 = pow(3.0, 9.0);//2 to the power of 4
    cout << num1 <<endl;
    num2 = rand() %100;//random number out of 100
    cout << "\nrandom number = " << num2 << endl ;

    return 0;
}
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
3

As Luchian said, move the function call into a scope .. in this case main. I have some other points. See the following code.

    #include <iostream>
    #include <cmath>
    #include <stdlib.h>
    #include <time.h>

    void myfun(int);//using own function

    void myfun(int x)
    {
        std::cout << "my favourite number is " << x << std::endl;
    }

    int main()
    {
        double num1, num2;

        srand(time(0));// to get a true pseudo-random number
        num1 = pow(3.0, 9.0);//2 to the power of 4
        std::cout << num1 << std::endl;
        num2 = rand() %100;//random number out of 100
        std::cout << "\nrandom number = " << num2 << std::endl ;
        myfun(8);//pow(4.0,10.0)

        return 0;
    }

Couple points:

  • It's generally considered a bad idea to do using namespace std; in a global scope. Much better to append std to names as needed to avoid cluttering your namespace and avoiding name collisions.
  • srand() doesn't really generate a true random number - just a pseudo-random number.
Chimera
  • 5,884
  • 7
  • 49
  • 81