The <ctime> header contains functions to get and manipulate date and time information. It is heavily used in scheduling applications, performance testing (benchmarking), and—most commonly for beginners—generating random numbers.
The time() function returns the current calendar time as a value of type time_t. This is usually represented as the number of seconds elapsed since the "Unix Epoch" (January 1, 1970).
#include <iostream> #include <cstdlib> // For rand() and srand() #include <ctime> // For time() using namespace std;int main() { // Seed the random number generator with the current time srand(time(0));
// Generate a random number between 1 and 100 int randomNum = (rand() % 100) + 1;
cout << "Your lucky number is: " << randomNum << "\n"; return 0; }
When using time functions, logic errors are far more common than syntax errors.
A very common mistake beginners make when generating random numbers is placing srand(time(0)) inside a for loop.
Because time(0) measures time in seconds, and computers execute loops in milliseconds, the time value won't change during the loop. The result? Your program will generate the exact same "random" number hundreds of times in a row!
The Fix: Always call srand(time(0)) exactly once at the very beginning of your main() function.
The value returned by time() represents seconds since 1970. This is a massive number that continues to grow. If you try to store it in a standard 32-bit int instead of time_t, it will eventually cause an "integer overflow" (famously known as the Year 2038 problem).
Why should you avoid placing `srand(time(0))` inside a fast-executing loop?