Merrill & Michele wrote:
#include <stdio.h>
#include <stdlib.h>
int main(){
int rnd;
long widernumber;
srand(time));
No definition of `time', and too many parentheses.
rnd=rand();
widernumber=(long)rnd;
printf=("wider number is %ld\n",widernumber)
Missing a semicolon.
return 0
Missing a semicolon.
}
Q1) Just so that I don't get ahead of myself, does the above code cast what
is necessarily an integer as a long?
After corrections, yes: `rnd' is an `int', and the cast
converts it to a `long'. The assignment would have converted
it anyhow, so the cast is not required.
Q2) What do the style people think about casts in general? MPJ
There are a few situations in which casts are necessary
or at the very least useful. However, they are greatly over-
used, and as a practical matter I tend to view each cast as
"guilty until proven innocent." For example, the cast in
your example is entirely unnecessary, and I take this as
evidence that you don't know what you're doing (which is all
right; that's why you're asking questions, after all).
"GUPI" also applies even when the cast is required,
because it suggests that the programmer is (ab)using C as a
kind of high-level assembly language, writing code that deals
with the representations of things rather than with their
values. Such code can (and frequently does) work as intended,
but tends to be non-portable: When the programmer "knows"
something the language doesn't promise, writes code that
exploits that "knowledge," and uses casts to get the compiler
to accept it, the code will misbehave if it's ever moved to
a system where the "knowledge" turns out to be false.
Casts are in a class with global variables: Sometimes
necessary, sometimes expedient, but always to be viewed
with suspicion.
--
Er*********@sun.com