5

Is it possible to send an array to a C function without declaring/defining it first?

This is possible with integers.

int add(int a, int b) {
    return (a + b);
}

void main(void) {
    int c;
    int a=1, b=2;

    /* With declaring (works fine)*/
    c = add(a, b);

    /* Without declaring (works fine)*/
    c = add(1, 2);
}

Is there anything along the lines of this for arrays?

#include <stdio.h>

void print_int_array(int *array, int len) {
    int i;
    for (i = 0; i < len; i++)
        printf("%d -> %d\n", i, *array++);
}

void main(void) {
    int array[] = {1, 1, 2, 3, 5};

    /* With declaring (works just fine) */
    print_int_array(array, 5);

    /* Without declaring (fails to compile) */
    print_int_array({1, 1, 2, 3, 5}, 5);
}
ryanmjacobs
  • 575
  • 1
  • 5
  • 9
  • Well presented 1st question, aside from it is a duplicate. To dig deeper, the example of `print_int_array(int *array, int len)`, IMO, is not a good use of a "compound literal" as such a function should be called with minimal interdependence as in `print_int_array(array, sizeof array/sizeof array[0]);` Not sure how a compound literal could then be used here. – chux - Reinstate Monica Jun 17 '14 at 19:30

2 Answers2

10

Yes. You can. In C99/11 you can do by using compound literals:

C11: 6.5.2.5 Compound literals:

A postfix expression that consists of a parenthesized type name followed by a braceenclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.99).

print_int_array((int[]){1, 1, 2, 3, 5}, 5);  

99) Note that this differs from a cast expression. For example, a cast specifies a conversion to scalar types or void only, and the result of a cast expression is not an lvalue.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
5

Yes, it is possible since c99 with a compound literal:

print_int_array((int [5]) {1, 1, 2, 3, 5}, 5);

( ){ } is the compound literal operator. Compound literals provide a mechanism for specifying unnamed constants of aggregate or union type. A (non-const) compound literal is modifiable.

ouah
  • 142,963
  • 15
  • 272
  • 331