Re: Sort of mystified from an earlier thread



Arctic Fidelity wrote:
> Chad wrote:
>
>> const char foo[] = "mystring";
>> char *constviol = strchr(foo,*foo); "
>>
>> char *strchr(const char *s, int c);
>>
>> When foo gets de-referenced (ie *foo), how come the compiler doesn't
>> complain about the difference between 'int' and 'char'?
>
> I have actually been wondering about this as well.

In C there is an implicit conversion from char to int.
This means that if there is a context expecting an int, but you
supply a char, then C will silently convert the char to an int.

Some people use this to call C a "weakly typed" language, and
say C has "holes in its type system". However those people are
usually Lisp trolls.

This means that the following code works:

char c = 5;
int i = c;
/* now 'i' has the value of 5 */

If C did not have this implicit conversion then you would have
to write something ugly like:

int i = (int)c;

To me, this is less type-safe than the real situation, as it
encourages the use of casts.

C also has an implicit conversion from int to char:

int i = 5;
char c = i;
/* now 'c' has a value of 5. */

But if 'i' had a value that couldn't be held by a char, then
we would have undefined behaviour (to cut a long story short).
Some compilers will issue a warning when you do a so-called
"narrowing conversion" like this.

C in fact has implicit conversions between all of the integral
and floating point types, with silent UB if the value can't
be represented.

By contrast, Java has implicit widening conversions, but no
implicit narrowing conversions. Java trolls often bring this up.

.



Relevant Pages