Print with variable or by direct account?

Asked

Viewed 45 times

1

Are these two methods the same in terms of performance? Is one better than the other or is it better in terms of code organization?

Method 01: direct

printf("%.4lf\n", sqrt( pow(x2-x1, 2) + pow(y2-y1, 2) ));

Method 02: per variable

    double dist;
    dist = sqrt( pow(x2-x1, 2) + pow(y2-y1, 2) );
    printf("%.4lf\n", dist);

1 answer

4


There is no right way. It is a matter of style and even need.

I tend not to create variables unnecessarily. But in complex calculations that have a clear meaning in more complex applications I can create a variable just to give it a name. And if the variable is created the name has to be as descriptive as possible, to do without greatly increasing the readability and making the code more obvious, do not create.

What I would never do is declare the variable in one row and assign in another.

Obviously if you are going to use the value in two different places, need an intermediate step or need to do something extra before using this value then the variable may be required.

In general it does not affect performance or memory consumption, but some more complex situations can rather be a little worse to create the variable. Nothing big and almost always unimportant, but there may be a difference.

Without seeing a context I would do the first, but I know that some people prefer to always do the second, with the caveats I have done before. If to do the second I would tend to create a function and so have this generic formula for general use.

  • The former was a simple just to apply the formula.. But I always had this doubt, thanks for the clarification.

  • Just one more question, what would be the reason you do not declare the variable after its creation?

  • Why do you do it? Don’t do things you can’t justify.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.