0

Edit: Changed bools to const bool, Added argument to anotherValueTest. May have oversimplified it before.

I am using a MSP430 and the integrated Compiler from the IAR Workbench. Link to workbench

Currently I am wondering whether there is any difference between the following code snippet.

const bool isValue1Good = (someValue1 > thresholdValue1);
const bool isValue2Good = (someValue2 < thresholdValue2);
const bool isThisTrue = anotherValueTest(value3);

const bool areValuesWithinWorkingArea = (isValue1Good && isValue2Good && isThisTrue);

if (areValuesWithinWorkingArea) {
    //do something
} else {
    // do something else
}

and this one:

if ((someValue1 > thresholdValue1) && (someValue2 < thresholdValue2) && anotherValueTest(value3)) {
    //do something
} else {
    // do something else
}

Will c++-compilers usually detect, that the bools are only used in this spot?

I read this topic regarding java where it seemed probable, that the first one is the better way, if the if-statements are getting bigger and more complicated. But also that the variables don't even get stored in the memory.

Putting the questions more clearly:

  1. Will the bools be stored inside the memory?
  2. If so, will they be stored there any longer than the ~1ns that the lines are evaluated?
  3. Will the compiler optimize the first example into the second one (or somewhat)?
  4. Will the compiled codes be of meaningful different size, if the total code is several ten thousand lines long?
  5. Are there any specific exemptions when working with small memory devices?
  6. Is this a topic where the compiler is very relevant or should (most) compilers behave the same due to basic rules regarding c++?
  7. Is there any worth-to-read article / documentation regarding compiler / c++-general behaviour regarding this topic, that I should look into?

The reason I ask this is, that I try to write my code as easy to read and maintain as possible, but currently some colleagues are "improving" stuff like this to reduce line-count. And I wonder whether I should be doing this as well or not.

kremerf
  • 21
  • 5
  • 7
    It really depends on the compiler, the optimization level, and the rest of the code. The as-if rule allows for these optimizations, whether or not they actually happen can only be found out after compiling and examining the generated assembly code. – NathanOliver Mar 20 '23 at 12:09
  • 1
    consider the as-if rule: If you cannot tell the difference from the observable behavior of the code, then the compiler is allowed to do the optimization. Whether it actually does the optimization is not guaranteed. The only way to be sure is to try and see – 463035818_is_not_an_ai Mar 20 '23 at 12:10
  • 1
    strictly speaking it depends on the types of variables you compare. An overloaded `<` might have side effects and `&&` is short circuiting. The two variants are not really equivalent – 463035818_is_not_an_ai Mar 20 '23 at 12:12
  • 1
    Difference in performance between these two ways of coding will be <= miniscule. – 500 - Internal Server Error Mar 20 '23 at 12:15
  • C++ compilers *may* eliminate any variables they choose, as long observable program output isn't affected (assuming your code has no undefined/unspecified/etc behaviours). Whether any particular compiler *does* or not - and when (e.g. optimisation settings) - are Quality of Implementation (QoI) concerns. Generally speaking, it is better to prioritise clarity/readability of your code and, where it matters, use instrumentation, testing, and profiling to identify where you need to code specifically for performance or memory usage instead of clarity. – Peter Mar 20 '23 at 12:18
  • 3
    7) [what exactly is the as if rule](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule) – 463035818_is_not_an_ai Mar 20 '23 at 12:20
  • Reducing line count is not the way to optimize code. Writing `i = 1; j = 2;` as a single line will definitely not make it run faster. – BoP Mar 20 '23 at 12:47
  • 1
    In general they are pretty good at detecting invariants and optimizing for those, so yes "optimize" your code for readability first (only optimize if you have a provable performance bottleneck). And in general performance is usually found in design not by squeezing the last cpu cycle out of your instructions. And Compilers may be "smarter" then you think : [what has my compiler done for me lately](https://www.youtube.com/watch?v=bSkpMdDe4g4). – Pepijn Kramer Mar 20 '23 at 12:51
  • 2
    Your second version only calls `anotherValueTest()` conditionally, as part of a short-circuit `&&`. Your first version calls it unconditionally. If it has any side-effects, or doesn't inline, then there will be some difference. But if `anotherValueTest()` does inline to something simple, I'd expect a good compiler to make decent code either way, not actually materializing `bool` temporaries into registers. – Peter Cordes Mar 20 '23 at 12:58
  • 2
    Extra parentheses and extra variables do not improve readability as _reliably_ as is sometimes claimed. Here, for example, I would definitely raise an objection to having non-const variables to which the reader must verify there are no assignments (as well as to introducing a new name for just a function call with no arguments if that’s not just a symptom of a simplified example—unless of course the order of evaluation matters, in which case a comment is in order). – Davis Herring Mar 20 '23 at 13:07
  • Thank you all for the quick responses. @PeterCordes I noticed that as well, the functions we use don't CHANGE anything, they just do calculations (that I like to write in 5-10 lines instead of putting them inside the if with magic numbers) and condense them to a bool, as we have lots of measurements and if one is off, we want the if-statement to be false. – kremerf Mar 20 '23 at 13:09
  • The answer to all your "will x happen" questions is "x may happen". This question would be objectively answerable if you were referring to specific code with a specific compiler. But to ask "Will c++-compilers usually..." hasn't set a clear enough target for this question because the scope is too general. Mentioning the existence of the as-if rule is probably the best that can be done for an answer, the way this is written. And asking for a recommendation for an article to read is cause to close the question. – Wyck Mar 20 '23 at 13:33
  • Then yeah, as long as the compiler knows that (e.g. because it can inline at compile time or with LTO, or it's declared with GNU C `__attribute__((pure))` or something), the optimization is possible. – Peter Cordes Mar 20 '23 at 13:34
  • @DavisHerring: Agreed; especially the final `bool areValuesWithinWorkingArea` is just clutter vs. putting its initializer as the `if()` condition. – Peter Cordes Mar 20 '23 at 13:37

0 Answers0