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++?

6
  • 2
    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? Commented Jul 11, 2020 at 19:35
  • 6
    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. Commented Jul 11, 2020 at 19:40
  • 1
    Have a look at this answer: stackoverflow.com/a/13562974/260313 Commented Jul 11, 2020 at 19:43
  • @rturrado so it's a duplicate :( sorry, I searched but did not see that one Commented Jul 11, 2020 at 19:45
  • 2
    @Anton Duzenko no probs, you always get some new and interesting comments and answers 😊 Commented Jul 11, 2020 at 19:47

1 Answer 1

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
  }};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.