Question

Let's say I have the following C struct:

typedef struct {
    float a, b;
} Floats;

I then have a function that will create instances of this struct:

Floats createFloats(float aVal, float bVal) {
    Floats f = {aVal, bVal};
    return f;
}

There are now essentially 4 possible (syntactic) ways of creating the same struct:

Floats f1 = createFloats(0.0f, 1.0f);             // (A) [Canonical?]
Floats f2 = createFloats(0.0, 1.0);               // (B)
Floats f3 = createFloats(0, 1);                   // (C)
Floats f4 = createFloats(((float)0), ((float)1)); // (D)

My question is, what compile-time and runtime differences are there between the above 4 methods of creating my struct? Specifically, when do the implicit float conversions occur (say for clang and gcc). I have been advised against (C) (and (D) seems overkill), but if the conversion happens at compile time, surely there is no difference between any of the above methods?

Was it helpful?

Solution

You can check such things quite simple. Compile your example into an object file with debug information and run objdump to disassemble it and display the assembly along with the C source code:

cc -g -c example.c
objdump -dS example.o

Doing that will for your example show that even without optimizations each variant produces exactly the same assembler code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top