I expected the following code to output 0 as it would in C:
u32(0.5) * 50
To my surprise this resulted in 25, which I think is a pretty cool language feature as it saves an extra type conversion to get to my desired behavior.
Can anyone explain whats going on behind the scenes and the rationale behind this design choice?
If you could include a short code snippet of that behavior, that might help to see what happened.
Not sure how that was possible:
u32 is not a float. A literal 0.5 cannot be cast to u32. Compiler should give: “Cannot cast ‘0.5’ as ‘u32’ from ‘untyped float’ 0.500000 cannot be represented without truncation/rounding as the type ‘u32’”
If an f32 for example is casted to u32, it is truncated like the below.
I originally stumbled upon this reading through a Vulkan guide for Odin. In the guide they were using a f32 ratio for each descriptor pool size:
for &ratio in pool_ratios {
sa.push_back(
&pool_sizes,
vk.DescriptorPoolSize {
type = ratio.type,
descriptorCount = u32(ratio.ratio) * max_sets, // <--- line in question
},
)
}
My first thought was that this couldn’t be right, so I tested it with literals:
fmt.println(u32(0.5) * 50)
Output: 25
That’s what bought me to my original question, but I have also realised just now when using variables, the original behavior I expected happens:
Output: 0
So I guess this is cool little feature the compiler has when the relevant information is available at compile time? and I am also starting to think this guide I am following is rather questionable…
I’ll just change this code to: u32(ratio * f32(max))
OK. This guide has done a great job of confusing the hell out of me.
The ratio meant how many descriptors of a given type are allocated per set, but my pea brain went to percentages on account of it being a f32. That begs the question why did the guide even make it an f32 in the first place?
My best guess about the guide using f32: the library they are interacting with wanted an f32 somewhere down stream for something else, but they wanted to reuse it in that specific case. I’ve been guilty of doing that. Just gotta be careful with casting.
I’m still unable to get the compiler to except a literal “u32(0.5)”. I wonder if the Odin version you are using is older than mine maybe?