Search code examples
cheader-filessrand

Is it a good idea to put srand() in the header file?


My program includes a function that uses rand(). That function will be called more than once so I can't put srand() at the beginning of the function. Now, is there a general rule that suggests whether srand() should be put in the header file of the function, or in the beginning of the main function?

My understanding is that both would work the same. The only difference is that if I want to reuse the function in the future, having srand() in the header makes the function more self-contained, but I may end up with multiple headers all having srand().

--Edit--

Yes, I mean something like

/*header.h*/
srand();
void my_funciton();

So it won't work?


Solution

  • Now, is there a general rule that suggests whether srand() should be put in the header file of the function

    If you mean something like

    /**
     * foo.h
     */
     srand();
    
     void my_function_that_uses_rand();
    

    that won't cause srand to be called by whatever includes the header file; it will be treated as an old-style implicit int function declaration (which will not work with C99 or later compilers, since implicit int function declarations are no longer supported), which will cause other problems if you've included math.h in whatever file is also including this file.

    EDIT

    Actually, it's worse than that, because a call to srand requires the seed parameter, so if you wanted to randomize on time, your header file would look something like

    /**
     * foo.h
     */
    srand(time(NULL));
    
    void my_function_that_uses_rand();
    

    which the compiler would immediately yak on, since srand(time(NULL)); is not a valid declaration in the first place.

    srand should be called once before the first call to rand, and it's up to the application code to do so. Note that if you always call srand with the same seed value, you will always get the same sequence of values in your rand calls.