Home > Blockchain >  Does this code make sense? C copy return vs ptr in
Does this code make sense? C copy return vs ptr in

Time:06-03

Which version of this code is better (or is there an even better way to do it)?

Copy out

void TranslatMat(float x, float y, float z) {
    Matrix matTranslation = {
       1.0f, 0.0f, 0.0f, x,
       0.0f, 1.0f, 0.0f, y,
       0.0f, 0.0f, 1.0f, z,
       0.0f, 0.0f, 0.0f, 1.0f };
    return matTransltion;
}

OR Ptr in

void rlTranslateMat(float x, float y, float z, Matrix *result) {
  *result = {
       1.0f, 0.0f, 0.0f, x,
       0.0f, 1.0f, 0.0f, y,
       0.0f, 0.0f, 1.0f, z,
       0.0f, 0.0f, 0.0f, 1.0f }; 
}

I just learned the rule of fifths and move constructors. Does that even apply here?

I know a 4x4 Matrix struct isn't huge but I plan to use this function every frame and this pattern for larger structs than a matrix.

CodePudding user response:

Matrix TranslatMat(float x, float y, float z) {

gives the most readable calling code

auto M = TranslatMat( x, y, z );

This will save you hours of work debugging your application

Once your application is working, then you can think about optimizing, but only code where time profiling shows it will make a significant improvement - likely not this code.

CodePudding user response:

The first example you are making a local matrix and then 'returning by value'. However, you have defined it as 'void'. This means you won't be able to return anything. If you attempted to compile the first example it will fail. to fix it you need to change type 'void' to type 'Matrix'

The second example you are passing a pointer to the function, directly modifying said data, then should return void (nothing).

There is no best case and to know which one to use.

  • If you are looking for a function to generate a matrix and you start working with it, lean towards the first example.
  • If you have an existing matrix and want to modify it, then you can use the second example.

However, given that this is c , you could also choose to pass by reference.

Given the nature of this question, I would recommend you to read up on: pass by value, pass by reference, and pass by pointer.

Afterwards, look into learning more about return types as well as dynamically allocated memory.

Once all of these are understood, then go back to the rule of 3 or 5 and move/copy constructors.

CodePudding user response:

Returning the matrix will be better because:

  1. it's more readable
  2. it allows copy elision
  3. it avoids potential aliasing with other Matrix * or float *

The last too will result in faster code.

Note: the compiler will turn it into ptr in if it can't optimize it, except it will use the structure return register instead of the 4th argument register.

  • Related