3

I have the following code in C that works just fine

typedef struct { float m[16]; } matrix;

matrix getProjectionMatrix(int w, int h)
{
  float fov_y = 1;
  float tanFov = tanf( fov_y * 0.5f );
  float aspect = (float)w / (float)h;
  float near = 1.0f;
  float far = 1000.0f;

  return (matrix) { .m = {
    [0] = 1.0f / (aspect * tanFov ),
    [5] = 1.0f / tanFov,
    [10] = -1.f,
    [11] = -1.0f,
    [14] = -(2.0f * near)
  }};
}

When I try to use it in C++ I get this compiler error: error C2143: syntax error: missing ']' before 'constant'

Why so and what's the easiest way to port the code to C++?

Anton Duzenko
  • 2,366
  • 1
  • 21
  • 26
  • 1
    [Designated Initializers](https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers) were added in the C++ 20 Standard revision, but I don't think that they allow array initializing like that. Does adding a constructor make any sense? – user4581301 Jul 11 '20 at 19:35
  • 5
    Do you _need_ to compile this file as C++? Perhaps you can compile it as C, leaving the rest of your app as C++. I do this for certain parts of my codebase and it works fine. – Paul Sanders Jul 11 '20 at 19:40
  • 1
    Have a look at this answer: https://stackoverflow.com/a/13562974/260313 – rturrado Jul 11 '20 at 19:43
  • @rturrado so it's a duplicate :( sorry, I searched but did not see that one – Anton Duzenko Jul 11 '20 at 19:45
  • 2
    @Anton Duzenko no probs, you always get some new and interesting comments and answers – rturrado Jul 11 '20 at 19:47
  • +1 for, with your question, teaching me something new in C -- and it is my 'mother tongue' in programming..... – Basya Jul 11 '20 at 21:42

1 Answers1

6

You're attempting to use a designated initializer which is allowed in C but not C++.

You'll need to explicitly initialize the individual members:

  return (matrix) { {
    1.0f / (aspect * tanFov ),
    0, 0, 0, 0,
    1.0f / tanFov,
    0, 0, 0, 0,
    -1.f,
    -1.0f,
    0, 0,
    -(2.0f * near),
    0
  }};
dbush
  • 205,898
  • 23
  • 218
  • 273