Search code examples
c++arraysccastingreturn

(C/C++) Initialize and return array in the same line


I was wondering how I could initialize and return an array on the same line using c/c++.

My intuition says that the syntax should look somewhat like this: return (int8_t*) {hours, minutes, seconds};

Am I correct? Is the cast mandatory? Or is there another/better way of doing this?

EDIT: I'm asking this because I cannot test the code right now. I won't be in front of a computer for some days.

ANSWER:

  • for C follow the steps in the verified answer
  • for C++ you would use a std::vector or std::array as the return type and then have return { 1, 2, ..., N };

Solution

  • This will not work as you expect.

    The exact syntax for what you're trying to do would be:

    return (int8_t []){hours, minutes, seconds};
    

    Which creates a compound literal of array type. However, this literal has the lifetime of the enclosing scope. So when the function returns, the returned pointer is now pointing to invalid memory, and attempting to dereference that pointer invokes undefined behavior.

    You'll need to dynamically allocate the memory, then assign each member of the array:

    int8_t *p = malloc(3 * sizeof(int8_t));
    p[0] = hours;
    p[1] = minutes;
    p[2] = seconds;
    return p;