Newbie question on time()

T

Todd Stephens

I am learning C from a tutorial book. The author explains how srand(time())
is a good way to generate a random number, and I have used it in a few
small example programs. I have come to a larger program that I am supposed
to modify, and in this sample code the author has used srand(time(NULL))
and in other places in the code has assigned time(NULL) to a couple of
variables. What does the NULL do in the time() function? It is not
necessary for me to know to complete this "assignment", but the author
fails to explain this sudden change in the code example and I am keen to
understand exactly what it is that I am looking at.
 
M

Mike Wahler

Todd Stephens said:
I am learning C from a tutorial book. The author explains how
srand(time())

The 'time()' function has one parameter, for which
an argument must be supplied by the caller. The call
you show above should not compile.
is a good way to generate a random number,

'srand()' does not generate a random number. It 'seeds' the
random number generator used by the 'rand()' function.

The value generated by 'time()' is often used as an argument
to 'srand()', as it produces the closest thing to a 'random'
value available to a standard C program.
and I have used it in a few
small example programs. I have come to a larger program that I am supposed
to modify, and in this sample code the author has used srand(time(NULL))
and in other places in the code has assigned time(NULL) to a couple of
variables. What does the NULL do in the time() function?

The time function returns a type 'time_t' object. Additionally
the address of a type 'time_t' object can be supplied as
an argument, in which case the same value which is returned
is also stored at that address. If this is not needed or
wanted, a NULL value can be passed instead, in which case
the parameter is ignored. It's a redundancy. I suppose
some might find a use for this behavior, but I never have.

It is not
necessary for me to know to complete this "assignment", but the author
fails to explain this sudden change in the code example and I am keen to
understand exactly what it is that I am looking at.

Change from what to what? 'time()' is a function in its
own right with various uses. The author was using its
return value as a seed for the random number generator.

I think you've mistakenly got the idea that 'srand()'
and 'time()' have some special relationship which does
not exist.

-Mike
 
T

Todd Stephens

Mike Wahler wrote in article
Change from what to what? 'time()' is a function in its
own right with various uses. The author was using its
return value as a seed for the random number generator.

Yes, but in earlier code examples, the author omitted the NULL assignment
and used simply srand(time()). I was confused when, in the next example,
he included it. You indicated that this would not compile without NULL,
but it did and the program ran fine. Here is the code from a silly
dice-rolling emulator:

#include <stdio.h>

main()
{

int intDie1 = 0;
int intDie2 = 0;
int intResult = 0;
srand(time());

intDie1 = (rand() % 6) +1;
intDie2 = (rand() % 6) +1;
intResult = (intDie1 + intDie2);

if (intResult == 7 || intResult == 11){
printf("\nYOU WIN!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
else{
printf("\nYOU LOSE!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
}

This code compiled and the resulting binary worked fine using gcc 3.2.3
I think you've mistakenly got the idea that 'srand()'
and 'time()' have some special relationship which does
not exist.

I wasn't really asking about any relationship between them. Just wondering
what the difference between using time(NULL) and time() is. So,
realistically I should use NULL whenever I call time() without wanting any
specific value to time()?
 
A

Al Bowers

Todd said:
Mike Wahler wrote in article



Yes, but in earlier code examples, the author omitted the NULL assignment
and used simply srand(time()). I was confused when, in the next example,
he included it. You indicated that this would not compile without NULL,
but it did and the program ran fine. Here is the code from a silly
dice-rolling emulator:

#include <stdio.h>

You are missing needed includes:
#include said:
main() int main(void)
{

int intDie1 = 0;
int intDie2 = 0;
int intResult = 0;
srand(time());

intDie1 = (rand() % 6) +1;
intDie2 = (rand() % 6) +1;
intResult = (intDie1 + intDie2);

if (intResult == 7 || intResult == 11){
printf("\nYOU WIN!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
else{
printf("\nYOU LOSE!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}

return 0;
}

This code compiled and the resulting binary worked fine using gcc 3.2.3

You did not get an error because you omitted the header, time.h, that
prototypes function time.
I wasn't really asking about any relationship between them. Just wondering
what the difference between using time(NULL) and time() is. So,
realistically I should use NULL whenever I call time() without wanting any
specific value to time()?

The synopsis for function time.
#include <time.h>
time_t time(time_t *timer);

So you see, function time takes an argument. The argument can
be a pointer to a time_t object or it can be a null pointer, time(NULL).
In the code, you omitted an argument and you also failed to include the
needed header which would have informed the compiler the correct
prototype for the function. Had you included time.h then the compiler
would have notified you with an error message.

Again, try the code with the includes. You should get an diagnostic.
 
T

Todd Stephens

Al Bowers wrote in article said:
Again, try the code with the includes. You should get an diagnostic.

OK. That code was basically the same as the author gave in the book with a
few things I threw in (mostly in the print statements). Why does the code
compile and the binary function if the code contains errors? Maybe I need
a different book. Any suggetions on a good 'Intro to C' book? I'm not too
interested in C++ at this point. I have some knowledge of VB and have done
a small bit of work in Python and Perl, so it need not be at the *most*
basic level.

I will try your suggestions and see what happens.
Al Bowers
Tampa, Fl USA

Hey, I'm in Lakeland.
 
M

Mike Wahler

Todd Stephens said:
Mike Wahler wrote in article


Yes, but in earlier code examples, the author omitted the NULL assignment
and used simply srand(time()).

If that is the standard library's 'time()' function,
then that is invalid statement.
I was confused when, in the next example,
he included it.

Perhaps it was a typographical error. Check to see
if an errata document is available for your book.
You indicated that this would not compile without NULL,
but it did and the program ran fine.

Then the 'time()' function you're calling is not the
one from the standard library, or your standard library
implementation is broken.
Here is the code from a silly
dice-rolling emulator:

#include <stdio.h>

main()

int main()
{

int intDie1 = 0;
int intDie2 = 0;
int intResult = 0;
srand(time());

No declaration of 'time()' in scope. A C90 compiler
will assume a return type of 'int'. A C99 compiler
must issue a diagnostic. A linker will complain about
undefined symbol 'time'.
intDie1 = (rand() % 6) +1;
intDie2 = (rand() % 6) +1;
intResult = (intDie1 + intDie2);

if (intResult == 7 || intResult == 11){
printf("\nYOU WIN!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
else{
printf("\nYOU LOSE!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
}

This code compiled and the resulting binary worked fine using gcc 3.2.3

Then you're either using some nonstandard function called
'time', or your standard library is noncompliant.
I wasn't really asking about any relationship between them.

It was a speculation.
Just wondering
what the difference between using time(NULL) and time() is.

The former is a valid call of the standard library function 'time()',
the latter is not.
So,
realistically I should use NULL whenever I call time() without wanting any
specific value to time()?

Please read again my description of the 'time()' function.
I described the 'time()' function from the C standard library.
If you're using something else, it's not standard and thus
not topical here.

-Mike
 
M

Mike Wahler

Todd Stephens said:
OK. That code was basically the same as the author gave in the book

"Basically the same" tells us nothing. What was it *exactly*?
with a
few things I threw in (mostly in the print statements). Why does the code
compile and the binary function if the code contains errors?

Um, nonstandard compiler?
Maybe I need
a different book.

Perhaps. Which book do you have?
Any suggetions on a good 'Intro to C' book?

www.accu.org
See the book review section under category "beginner C"
I'm not too
interested in C++ at this point.

No problem. C++ is not C.
I have some knowledge of VB and have done
a small bit of work in Python and Perl, so it need not be at the *most*
basic level.


See above.

Also see the welcome message for comp.lang.c:
http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html

and the C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html

Much useful information at both links for C programmers
of all levels of experience.


I will try your suggestions and see what happens.

Rather than "try and see", I recommend you get a good
book, and you can *know* what will or will not happen
with a particular piece of code.

HTH,
-Mike
 
A

Al Bowers

Todd said:
OK. That code was basically the same as the author gave in the book with a
few things I threw in (mostly in the print statements). Why does the code
compile and the binary function if the code contains errors? Maybe I need
a different book. Any suggetions on a good 'Intro to C' book? I'm not too
interested in C++ at this point. I have some knowledge of VB and have done
a small bit of work in Python and Perl, so it need not be at the *most*
basic level.

I will try your suggestions and see what happens.

It seems you are on the right tract. Remember, a compiler, does not
define the C Language. Just using your compiler to determine the
validity of code will get you in trouble. The International Standard
ISO/IEC 9899 defines the C Language. So, resources like a copy of
the Standard or books that explain the standard is the right approach.
Personallly, my favorite resources are the Standard itself, 'The C
Progamming Language' (Second Edition), "The Standard C Library', and
finally the FAQ which can be found on the web at:
http://www.eskimo.com/~scs/C-faq/top.html

OK, Getting back to the code you supplied: Here it is again.

/*************** test.c *************/
#include <stdio.h>

main()
{

int intDie1 = 0;
int intDie2 = 0;
int intResult = 0;

srand(time());

intDie1 = (rand() % 6) +1;
intDie2 = (rand() % 6) +1;
intResult = (intDie1 + intDie2);

if (intResult == 7 || intResult == 11){
printf("\nYOU WIN!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
else{
printf("\nYOU LOSE!!\n");
printf("First roll was %d and second was %d\n", intDie1, intDie2);
}
}

You said that when you compiled it with GCC 3.2.3 that it compiled and
the binary worked fine. When you compiled it did the compiler give
you any warning diagnostics? If gcc did not give you any warnings
perhaps you should increase the warning level. I compiled the above
code with gcc 3.2 and with a high level of warning. The command was:
gcc test.c -pedantic -Wall
The code compiled and a binary was built. However, I got five warning
messages. They were:

Line 4: warning, return type defaults to 'int'
In function 'main':
Line 9: warning, implicit declaration of function 'srand'
Line 9: warning, implicit declaration of function 'time'
Line 11: warning, implicit declaration of function 'rand'
Line 23: warning, control reaches end of non-void function.

The line 4 warning is the result of not explicitly declarating
function main returning an integer: int main()

The Line 9 warnings(2) is the result of not including the headers,
stdlib.h for function srand and time.h for function time. These
headers have the declarations for these functions.

The line 11 warning is the same as line 9. You did not include the
header stdlib.h which declares function rand.

The Line 23 warning is the result of function main not returning
an int. So you should return an integer, like 'return 0' at the
end of the function.

So you see, the resource that supplied you with this code has
serious deficiencies. You should seek additional resources like I
mentioned above.
 
T

Todd Stephens

Mike Wahler wrote in article
"Basically the same" tells us nothing. What was it *exactly*?
If there was no #include of <time.h> and no argument passed to
it, then its simply wrong.


Um, nonstandard compiler?

gcc 3.2.3, but I did not have any high warning levels turned on.
Perhaps. Which book do you have?

"C Programming for the Absolute Beginner" by Michael Vine
www.accu.org
See the book review section under category "beginner C"

I'll have to check that out.
Also see the welcome message for comp.lang.c:
http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html

and the C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html

Much useful information at both links for C programmers
of all levels of experience.

Thanks for the links.
Rather than "try and see", I recommend you get a good
book, and you can *know* what will or will not happen
with a particular piece of code.

It is becoming apparant to me that the book I have is using some sort of
hackneyed approach to the code. I know the K&R book is the definitive
guide, but I am led to believe it is not so good for teaching from the
ground-up in C. Still, I shall probably get a copy of it and see how it
feels.
 
T

Todd Stephens

Al Bowers wrote in article said:
So you see, the resource that supplied you with this code has
serious deficiencies. You should seek additional resources like I
mentioned above.

I shall do just that. I flipped through the rest of the book thinking that
maybe the author used this as merely an early example, but the code
throughout the whole book is missing quite standard pieces. Not once in
the whole book is the main() declared as anything other than just "main()"
and no return value is ever declared either.
 
C

CBFalconer

Todd said:
.... snip ...

It is becoming apparant to me that the book I have is using some
sort of hackneyed approach to the code. I know the K&R book is
the definitive guide, but I am led to believe it is not so good
for teaching from the ground-up in C. Still, I shall probably
get a copy of it and see how it feels.

If you have a reasonable idea of what programming is about K&R is
an excellent teaching tool. It probably remains the best
introduction to C, and even generic reference, that there is.
That is why it has sold for 25 years, with a single revision 15
years ago.

Don't forget to get the errata, published at:

<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html>
 
T

Todd Stephens

CBFalconer wrote in article said:
If you have a reasonable idea of what programming is about K&R is
an excellent teaching tool. It probably remains the best
introduction to C, and even generic reference, that there is.
That is why it has sold for 25 years, with a single revision 15
years ago.

I reread all the reviews on Amazon.com, and found a study/answer guide
companion that goes with it. That looks like a good combination to me, but
I'll have to do some penny-pinching for a while to gather the USD80 that
I'll need. Thanks to everyone for their insight and help with this.
 
J

Jeremy Yallop

Todd said:
I reread all the reviews on Amazon.com, and found a study/answer guide
companion that goes with it. That looks like a good combination to me, but
I'll have to do some penny-pinching for a while to gather the USD80 that
I'll need. Thanks to everyone for their insight and help with this.

It's also worth reading Steve Summit's notes alongside K&R:

http://www.eskimo.com/~scs/cclass/krnotes/top.html

Jeremy.
 
C

CBFalconer

Todd said:
I reread all the reviews on Amazon.com, and found a study/answer
guide companion that goes with it. That looks like a good
combination to me, but I'll have to do some penny-pinching for a
while to gather the USD80 that I'll need. Thanks to everyone
for their insight and help with this.

You don't need any separate study/answer guide. It goes for about
USD40 or so. You might check Barnes and Noble for second hand
copies. Our own Richard Heathfield publishes a set of answers on
his pages.
 
F

Floyd Davidson

Default User said:
However, it was not a reasonable correction of the posted code.

Your point is well taken because the two are both equally
acceptable per the Standard, which says,

5 Finally, control is returned to the host environment.
If the value of status is zero or EXIT_SUCCESS, an
implementation-defined form of the status successful
termination is returned. If the value of status is
EXIT_FAILURE, an implementation-defined form of the status
unsuccessful termination is returned. Otherwise the status
returned is implementation-defined.

To me that indicates (as far a C is concerned) there are only
two possible values of status that can be returned, _successful_
and _unsuccessful_. And either a "zero or EXIT_SUCCESS" result
in a unique, singular _successful_ status, making them
necessarily equal.

However, Ben Pfaff is certainly teasing us with something
specific in mind, and I would like to hear him expand on it
because obviously there is more to this than I'm seeing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top