The ANSI C grammar from -link- give me the following rules for array declarations:
(1) | direct_declarator '[' type_qualifier_list assignment_expression ']'
(2) | direct_declarator '[' type_qualifier_list ']'
(3) | direct_declarator '[' assignment_expression ']'
(4) | direct_declarator '[' STATIC type_qualifier_list assignment_expression ']'
(5) | direct_declarator '[' type_qualifier_list STATIC assignment_expression ']'
(6) | direct_declarator '[' type_qualifier_list '*' ']'
(7) | direct_declarator '[' '*' ']'
(8) | direct_declarator '[' ']'
Now I have a some questions about these:
- Can I use (1) – (6) except (3) only in C99?
- What are (4) and (5) for? The keyword ‘static’ confuses me.
- Where to use (6)?
-
What’s the difference between the following two function prototypes:
void foo(int [*]);andvoid foo(int []);
Thank you.
You can’t use type qualifiers or
staticin size portion of array declaration in C89/90. These features are specific to C99.staticin array declaration tells the compiler that you promise that the specified number of elements will always be present in the array passed as the actual argument. This might help compilers to generate more efficient code. If you violate your promise in the actual code (i.e. pass a smaller array), the behavior is undefined. For example,The
*in size portion of array declaration is used in function prototype declarations only. It indicates that the array has variable length (VLA). For example, in the function definition you can use a VLA with a concrete run-time sizeWhen you declare the prototype you can do the same
but if you don’t specify the parameter names (which is OK in the prototype), you can’t use
nas array size of course. Yet, if you still have to tell the compiler that the array is going to be a VLA, you can use the*for that purposeNote, that the example with a 1D array is not a good one. Even if you omit the
*and declare the above function asthen the code will still work fine, because in function parameter declarations array type is implicitly replaced with pointer type anyway. But once you start using multi-dimensional arrays, the proper use of
*becomes important. For example, if the function is defined asthe the prototype might look as follows
or as
In the latter case the first
*can be omitted (because of the array-to-pointer replacement), but not the second*.