rand() strange behavior when in another function

I am using modulus 6 plus 1 on rand() to generate numbers from 1 to 6 through a function call. But the function returns 004111E5. I don't know why the rand() doesn't behave the way it should once it is in another function. Can someone enlighten me please? I am using Visual Express 2010. The following is the code. Thank you.

#include "iostream"
#include "cstdio"

using namespace std;

int rand_num(int); // Prototype for the rand() function within another function

int main()
{
cout << rand_num << endl;

return 0;
}

int rand_num(int numX) // rand() function in another function named rand_num()
{
numX = rand() % 6 + 1;

return numX;
}
1
2
#include "iostream"
#include "cstdio" 

really should be
1
2
#include <iostream>
#include <cstdlib> 

(you don't need cstdio but you do need cstdlib. I doubt this even compiled, unless you wrote some headers).

Also, your rand will always return the same values because you didn't seed it with something unique, like the number of seconds since January 1st 1970.
http://cplusplus.com/reference/clibrary/cstdlib/srand/
http://cplusplus.com/reference/clibrary/ctime/time/
You need to #include <ctime>.

-Albatross
Last edited on
You are not calling the rand_num() function here:

 
cout << rand_num << endl;


You are printing out its address in memory....

I think you want to do this instead:


 
cout << rand_num() << endl;


And, on top of that, your rand_num() function looks awkward. Why do you pass in a variable x? That is not needed at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> // angle braces
#include <cstdio>

using namespace std;

int rand_num(); // Note, no parameter

int main()
{
    cout << rand_num() << endl; // use () to call the function rather than use its address.

    return 0;
}

int rand_num() // rand() function in another function named rand_num()
{
    int numX; // declare this here, NOT as a parameter.

    numX = rand() % 6 + 1;

    return numX;
}
Last edited on
You are not calling the rand_num() function here:


cout << rand_num << endl;


You are printing out its address in memory....

I think you want to do this instead:


cout << rand_num() << endl;


I spent 3 hours trying to understand what I'm doing wrong. So address [without ()] vs value [with ()], I got it.
So square brackets for the header files? Some of my Visual Express 2010 had it in double quotation marks and did not take in the square brackets, so I thought that people are switching from one practice to another. Thanks for the help, both of you.

The angle brackets <string> tell the compiler pre-processor to look in the system-defined place for header files.

But quotes "string" tell the compiler pre-processor to look relative to the file's directory.

Topic archived. No new replies allowed.