What is the difference between these expressions?

3

In the srand manual man srand it says that srand has a unsigned int as its parameter, however when using it without cast the compiler does not complain. Is it possible to go wrong if you do not use cast (unsigned int) ? If yes, what are the possible errors?

An example, comparing the two lines of code below:

srand(time(NULL));
srand((unsigned int)time(NULL));
    
asked by anonymous 30.08.2014 / 07:12

2 answers

2

He is casting implicitly, which has no problems in some cases.

For example:

int x = 3;
double y = 4.5;
x = x + y;

What happens in these cases and the following:

1. Na soma de 'x' com 'y', 'x' e promovido para 'double' e a soma acontece como se ambos fossem desse tipo;
2. O resultado da soma, 7.5, e convertido de volta para 'int', ja que 'x' e do tipo inteiro.

Normally, the compiler does these operations implicitly. You can also do it explicitly, for example:

int x = 65;
printf("%c\n", (char)x);

Now, we interpret x as char to print, then its value of A .

There are, however, cases where these implicit conversions are wrong, especially with pointers.

    
30.08.2014 / 07:33
1

When you add the header that contains the declaration of the function srand() (the header stdlib.h ) the compiler knows the type of the parameter.

Then it converts the type you used to the required type, if possible. If it is not possible give a message.

#include <stdlib.h>
int main(void) {
    srand(42); // ok
    srand(4.2); // ok, conversao de 4.2 para 4
    srand(srand); // NOT ok! nao é possivel converter pointers para unsigned
}

If you remove #include they are all bad even though the compiler does not complain

    
30.08.2014 / 10:09