Iterate through function arguments using a pointer to the first

I would like to know if the following C code adheres to the C99 and / or C11 standard (s):

void foo(int bar0, int bar1, int bar2) { int *bars = &bar0; printf("0: %d\n1: %d\n2: %d\n", bars[0], bars[1], bars[2]); } int main(int argc, char **argv) { foo(8, 32, 4); return 0; } 

This piece of code compiles and works as expected when using visual studio 2013 and prints:

0: 8
1: 32
2: 4

+6
source share
3 answers

No, not anywhere near.

Standard

C does not guarantee that function arguments are stored in sequential memory cells (or, in any case, in any particular order). The compiler and / or platform (architecture) needs to decide how the arguments of the function are passed to the function.

To add even more clarity, there is no guarantee that the arguments passed are stored in memory (for example, on the stack) in general. They can also use hardware registers (when applicable) for some or all of the parameters to quickly perform operations. For instance,

  • Powerpc

    The PowerPC architecture has a large number of registers, so most functions can pass all arguments in registers for single-level calls. [...]

  • MIPS

    The most commonly used call for 32-bit MIPS is O32 ABI, which passes the first four arguments of a function to the registers $a0 - $a3 ; subsequent arguments are pushed onto the stack. [...]

  • X86

    The x86 architecture is used with many different calling conventions. Due to the small number of architectural registers, x86 calling conventions mostly pass arguments on the stack, and the return value (or pointer to it) is passed to the register.

etc. Check out the full wiki here .

So, in your case, bars[0] is a valid access, but whether bars[1] and bars[2] valid depends on the underlying environment (platform / compiler). Better not rely on the behavior you expect.

However, just for nitpick, if you are not going to use the arguments (if any) passed to main() , you can simply reduce the signature to int main(void) { .

+11
source

No, it does not comply with any published standard. How arguments and local variables are stored, and where before the compiler. What may work in one compiler may not work in another or even in a different version of the same compiler.

The C specification does not even mention the stack; all it defines is scope rules.

+7
source

No standard supports this. It is very naughty.

Array indexing and pointer arithmetic are valid only for arrays. (Note the slight exception: you can read the pointer after an array or scalar, but you cannot respect it.)

+5
source

All Articles