When defining structs in C, there are considerations regarding padding, if struct size is a concern, its common to re-arrange the values to avoid padding. (see: Structure padding and packing)
My questions is:
Do the same (or similar) rules apply to function arguments? ... is there any advantage in arranging arguments to avoid argument padding bytes?
Assuming this isn't an inline
(where it wont matter), or static
function where the compiler could re-arrange arguments.
Accepting that the real world measurable improvement is likely to be small.
... in practice if function call overhead is a concern, it may be worth inlining the function. nevertheless, inlining isnt always an option (libraries or function pointers for eg).
Yes, it matters. The arguments must be given in the order the function expects them. C passes arguments by value. It has no way of associating a value with an argument other than by position.
What is alignment? Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory. First we must conceptualize main memory as a contiguous block of consecutive memory locations. Each location contains a fixed number of bits.
Neither the C nor C++ standard places an absolute requirement on the number of arguments/parameters you must be able to pass when calling a function, but the C standard suggests that an implementation should support at least 127 parameters/arguments (§5.2.
Arguments passed to a C function are pushed onto the stack, right to left, before the function is called. The first thing the called function does is push the EBP register, and then copy ESP into it. This creates a new data structure normally called the C stack frame.
If the argument is small enough to be passed in a register, then the size is immaterial.
Generally the answer is no because compilers often widen arguments when they are passed on the stack to a function. For example:
So it doesn't pay to group your one and two byte arguments together because either the argument will be passed in a register or the compiler will probably treat them as being four or eight bytes in length anyway.
How arguments are passed to a function varies from architecture to architecture, so it's not possible to provide any sort of definite answer. However, for most modern architectures, the first few parameters are passed in registers, not on the stack, and it matters little how the parameters are aligned, because narrow arguments are not multiplexed into a single register.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With