I'm trying the following code. The line with the error is pointed out.
int[] myfunction() { { //regular code } catch (Exception ex) { return {0,0,0}; //gives error } }
How can I return an array literal like string literals?
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
Compound literals were introduced in C99 standard of C. Compound literals feature allows us to create unnamed objects with given list of initialized values. In the above example, an array is created without any name. Address of first element of array is assigned to pointer p.
Array literalsAn array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
Return an array of int
like this:
return new int [] { 0, 0, 0 };
You can also implicitly type the array - the compiler will infer it should be int[]
because it contains only int
values:
return new [] { 0, 0, 0 };
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