Hello, I should start off by saying I am new to C++ and recently started my first semester in it. I think my question is simple, but I am not sure how to really ask it. I want to know which way is the correct way to make a calculation in my program. I coded it one way and someone in class said it seemed weird even if it worked so I tried it another way. It works both ways, so I guess my question is which way should I write it?
//Calculates the total profit for one of each item
itemProfit1 = itemUp1 - itemCost1;
itemProfit2 = itemUp2 - itemCost2;
itemProfit3 = itemUp3 - itemCost3;
//Calculates the profit for a whole stock of the item
totalProfit1 = itemProfit1 * itemStock1;
totalProfit2 = itemProfit2 * itemStock2;
totalProfit3 = itemProfit3 * itemStock3;
//Calculates the total Profit from all items
wholeProfit = totalProfit1 + totalProfit2 + totalProfit3;
If they both work, that's great; just pick the way you prefer and do that.
However, remember that code is not just something for the compiler to compile; it's also something for humans to read. If your code is difficult to understand, it will be easier to make mistakes, harder to find mistakes, harder to change later and harder for someone else to come in and do these things.
Of course, spreading things across many more variables and more code will cause changes in the final compiled code; size, speed, all that sort of things can be affected.
Remember, comments are free! You can use as much commentary as you like and it won't affect the compiled code.
There is a trade off to be made and it's up to you to find the best overall style of coding, bearing in mind the needs of the specific requirements at hand. Good luck :)
int X( 3 + ( 3 + 4 ) ); // '+' in ( 3 + 4 ) has a higher precedence.
Adding parentheses around a computation changes the precedence of the used operator( s ) at the time of the computation temporarily during runtime. Other than that, you can use any style you want.