- Related Questions & Answers
- Selected Reading
C++ How To Use Srand
Srand.; 2 minutes to read; In this article The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com. The latest version of this topic can be found at srand. Sets the starting seed value for the pseudorandom number generator. The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand. Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: randr (non-portable). C library implementations are allowed to guarantee no data races for calling this function.
rand()
การเขียนโปรแกรมสุ่มเลข หรือrandom ในภาษา c, c จะใช้ 2 function หลักๆคือ.
The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.
Here is the syntax of rand() in C language,
Here is an example of rand() in C language,
Example
Output
srand()
The function srand() is used to initialize the generated pseudo random number by rand() function. It does not return anything.
Here is the syntax of srand() in C language,
Here is an example of srand() in C language,
Example
Output
-->The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at srand.
Sets the starting seed value for the pseudorandom number generator.
Syntax
Parameters
seed
Seed for pseudorandom number generation
Remarks
The srand
function sets the starting point for generating a series of pseudorandom integers in the current thread. To reinitialize the generator to create the same sequence of results, call the srand
function and use the same seed
argument again. Any other value for seed
sets the generator to a different starting point in the pseudorandom sequence. rand
retrieves the pseudorandom numbers that are generated. Calling rand
before any call to srand
generates the same sequence as calling srand
with seed
passed as 1.
Requirements
Routine | Required header |
---|---|
srand | <stdlib.h> |
For additional compatibility information, see Compatibility in the Introduction.
Example
C++ Srand 1 10
See the example for rand.
.NET Framework Equivalent
Dev C++ Srand
See Also
Dev C++ Random
Floating-Point Support
rand