473,796 Members | 2,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casts for srand? (FAQ 13.17)

"Each time I run my program, I get the same sequence of numbers back
from rand()."
The answer to question 13.17, in the c-faq is:

#include <stdlib.h>
#include <time.h>

srand((unsigned int)time((time_ t *)NULL));
Are all those casts in the srand() call really needed?
Is this ok, instead, relying on implicit casts when needed?

#include <stdlib.h>
#include <time.h>

srand(time(NULL ));
/* or even
srand(time(0));
*/
PS: According to the standard, does <stdlib.h#defin e NULL?
Jan 8 '08 #1
2 2139
On Tue, 08 Jan 2008 12:08:44 -0800, Mara Guida wrote:
"Each time I run my program, I get the same sequence of numbers back
from rand()."

The answer to question 13.17, in the c-faq is:

#include <stdlib.h>
#include <time.h>

srand((unsigned int)time((time_ t *)NULL));

Are all those casts in the srand() call really needed? Is this ok,
instead, relying on implicit casts when needed?
A cast is an explicit conversion. An implicit cast would be an implicit
explicit conversion.

But no, there's nothing wrong with relying on the implicit conversion
from 0 or NULL to time_t *, and from time_t to unsigned int. Depending on
the implementation, the casts may affect some diagnostics, but no bugs
will be introduced or fixed by them.
PS: According to the standard, does <stdlib.h#defin e NULL?
Yes. NULL is defined by <stddef.h>, <stdio.h>, <stdlib.h>, <string.h>,
<time.h>, <wchar.h>, and <locale.h>. It's harder to include standard
headers and _not_ get NULL defined, than it is to accidentally leave it
undefined.
Jan 8 '08 #2
In article <9d************ *************** *******@r60g200 0hsc.googlegrou ps.com>,
Mara Guida <ma*******@gmai l.comwrote:
>"Each time I run my program, I get the same sequence of numbers back
from rand()."

The answer to question 13.17, in the c-faq is:

#include <stdlib.h>
#include <time.h>

srand((unsigne d int)time((time_ t *)NULL));

Are all those casts in the srand() call really needed?
No. They're probably there for historical reasons.

>Is this ok, instead, relying on implicit casts when needed?
There's no such thing as an "implicit cast"; a cast is a source code
construct (and therefore inherently explicit) that forces a
conversion.
That nitpick aside, assuming you meant "implicit conversion", the
answer to your question is yes, it's perfectly valid.

>#include <stdlib.h>
#include <time.h>

srand(time(NUL L));
/* or even
srand(time(0)) ;
*/
If you forgot to #include <time.h>, you won't have a prototype in scope
for time(), and these would pass an integer 0 (or possibly a null void *)
instead of a null time_t *. Pre-ANSI C would have required a cast here
to force the right type to be passed, but now that we have prototypes
(and have for almost two decades) the correct solution is to
#include <time.hand let the compiler do the conversion for you.

Casting the return value is slightly less useless, but only slightly;
time_t (which time() returns) is required to be an arithmetic type, and
every arithmetic type can be converted to unsigned without a cast, but
your compiler might warn about some of them and the cast will tell it
to be quiet (which is in general not such a good idea, but is probably
valid here).
dave

Jan 8 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
653
by: David Shaw | last post by:
Hi, I'm writing a fun little program to play "Petals Around the Roses" with... I need to seed my random numbers so that they won't be the same every time I run the program, but my compiler won't let me. Here's the output my compiler generated...: -- Compiler: Default compiler Executing g++.exe... g++.exe "C:\Documents and Settings\rmarkoff\Desktop\roses.cpp" -o "C:\Documents and Settings\rmarkoff\Desktop\roses.exe"
5
2795
by: Andrew | last post by:
Hello, Is there anyway to detect when scanf implicitly casts a value? If I have a scanf call which expects a float and is passed a double I believe that testing the scanf call with if(scanf("%f",&val) == 1) would be true, but the double would have been truncated to a float. Is there anyway to flag this cast? Thanks
20
2328
by: Martijn | last post by:
Hi, Those familiar with Windows programming may be familiar with the windowsx.h header. In this header macros exist that use double casts, like so (hope this is readable): #define ComboBox_LimitText(hwndCtl,cchLimit) \ ((int)(DWORD)SendMessage((hwndCtl),CB_LIMITTEXT,(WPARAM)(int)(cchLimit),0))
25
2744
by: Merrill & Michele | last post by:
Many of us watched the World Series of Poker this last week and plotted how we were to take over that world. My current problem begins with shuffling the deck. For the apps I've written before, I've always been satisfied with the usual: #include <time.h> #include <stdio.h> int main( 2 things) {
3
2178
by: bobrics | last post by:
Hi, I am using srand() and would like to create different random numbers during a SINGLE execution of my program because I want to compare random cases. For now I have a switch statement within a loop, which does not do the job. I get the same output from my simulator every time. Does it mean that it actually can seed ONCE per program run? Thanks
11
7722
by: jtagpgmr | last post by:
I am currently using the gcc compiler on a cygwin platform, I am a beginner when it comes to programming in C and want to know why anytime I run the .exe with the following code I get a "segmentation fault (core dumped)" error: #include <stdio.h> main() {
61
2821
by: jacob navia | last post by:
Continuing the discussion about casts, I would like to know your opinions about the hairy subject of casts as lvalues, i.e. This will fail under lcc-win32, but MSVC and gcc will accept it. I know that the standard prescribes the behavior that lcc-win32 uses, but I left that behavior after a big discussion about this several years ago. I had modified it, and some people raised hell.
35
2101
by: =?utf-8?b?QXNiasO4cm4gU8OmYsO4?= | last post by:
This topic is a FAQ. But I have read the faq and spent a couple of hours browsing the group archives, and still have a few questions that I hope you can answer. My understanding is that recommended practice is to not cast the return value from malloc(). The rationale for this is that 1) the cast is not needed and 2) the cast may mask errors. I assume that the reason the cast is not needed has to do with the fact that the the pointer...
20
3860
by: Bill Cunningham | last post by:
I am stumped on this one. I tried two methods and something just doesn't seem right. I'll try my new syle. #include <stdio.h> #include <stdlib.h> main() { srand(2000); /*seed unsigned */ printf("%u",rand()); }
0
10465
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10242
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7558
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6800
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4127
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2931
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.