You are here:

C++/Random Integer


I'm using a free version of microsoft visual c++ and whenever I use the rand() function under the <cstdlib> the random number is always 41. Why? How do I fix that?

Alex Carruthers , Thank you for your question.

1. There is no free version of Visual C++. Microsoft charges money for this product, even for the Academic (Student) Edition.

2. You should not use <cstdlib>. This file simply Includes <stdlib>, in which "rand" is declared.

3. "rand" should not always return  41. Perhaps you forgot to call the "srand" function first. From the MSDN Library:

"_Return Value_

rand returns a pseudorandom number, as described above. There is no error return.


The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Use the srand function to seed the pseudorandom-number generator before calling rand."

I hope this information helps.

David Spector


All Answers

Answers by Expert:

Ask Experts


David Spector


Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.


I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 All rights reserved.