Sign in to follow this  

quick question

Recommended Posts

where does the number randomly selected by rand go? =) I mean, when the random number is selected, how do I use it? I read the tutorial on but I cant see where the randomly selected number is called. Maybe I have a weird problem? btw thanks to ppl who help me yesterday

Share this post

Link to post
Share on other sites
rand() is a function. Notice the two parenthesis after it. This means that it's a chunk of code somewhere else that can be called. When you call the function, it runs said chunk of code. Functions can also return a value. That is, once the chunk of code is done running, it gives the code that called it back a value. This value is placed where the function call is. rand() is calling the function rand. When it's called, it runs some code off somewhere that you don't need to see. When it's done, it returns the new random number.

Imagine that the '+' operator was a function (it is! But it looks odd). The function goes runs some code where you can't see that adds two numbers, and then returns the sum. When you evaluate '2 + 3', you get the sum, 5. The same thing happens with rand(), except that instead of summing something, it just chooses a random number. Just as you can assign '2 + 3' to a variable, you can assign rand().

int a = 2 + 3;
int b = rand();

It's the same principle. Just as 2 + 3 evaluates to 5, rand would evaluate to some random number. 5 becomes where '2 + 3' is, and is then given to the variable a. Similarly, the random number becomes where the function call is, which is then given to the variable b.

You can, naturally, do things to the value returned by rand(). Such as add three, take the modulus of it and 10, or divide by 2.3.

int c = rand() % 10 + 1;

And now we are where Talroth is.

Hope that helps.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this