13 ms·
int f(float x) { return *(int *)x; }
by yuubi 12y ago
int f(float x) {
return *(int *)x;
}
- vidarh 12y agoThat program refuses to compile not because you can't cast to/from arbitrary types in C, but because you don't make your intent explicit (assuming I read what you tried to do correctly). Try this: int f(float x) { return *(int *)&x; } On one hand you demonstrate that C cares a tiny little bit about type, but mostly because of implicit numeric conversions rather than any serious attempt at stropping you from bad casting. I do agree with the point that C isn't "typeless" in any real sense, though.
- jeorgun 12y agoI think the original was intentional. If C refuses to let you cast from a non-pointer to a pointer, then it is in fact enforcing some (small) degree of type-safety.
- vidarh 12y agoThe reason I assumed it was not, is that obtaining the bitwise representation of a float is something people actually often ask for (and my variation is not the "right" way to do so). You may be right C does not refuse to let you cast from a non-pointer to a pointer either, though. It just forces you to be slightly more devious in this case: return *(int **)&x; Though I think the implicit conversions that force some of these contortions (e.g. "(int *)(int)x" compiles, but does not return an integer pointer with the address equal to the bit pattern of "x" interpreted as an integer, but the integer portion of the float reinterpreted as a pointer) are more convincing demonstration that C is not typeless in a meaningful way in my opinion, as they also mean identical statements will give different results depending on the types of the variables.
- vegedor 12y agoWell, you are laying of the safety belt there, don't complain afterwards. It make sense to me in some cases, so i won't even argue.
- deleted 12y ago[deleted]
- yuubi 12y agoThe intent was to show that (at least one implementation of) C does stop a completely nonsensical cast from float to pointer, not to demonstrate anything semi-sensible like getting the bits of a float.