Question number 1:
The &&
operator has precedence over ||
, so it will be evaluated first. Both terms (++i
and ++j
) have pre-increment, so first they are increased to -2 and 3 respectively, then they are ANDed. In C++, 0 is false
and everything else is true
. In this case, both terms are true
(that is, non-zero), so the &&
returns true
. Now it's time to test true || ++k
. Here, an optimization kicks in: since true || anything
will always be true
, the compiler doesn't even test the expression. That is, it doesn't execute it. And k
is not incremented. That's why it is a very bad habit to have the code inside if-statements do something - you can't be sure it will be run, depending on the condition. If you need it to run, make sure it is not put there or it could be optimized away.
Question number 2:
Floating point arithmetics is tricky - representing a number exactly is often not possible, and the numbers that are really used are just a very close approximation - close enough that it looks like it works, but if you go checking every small bit you notice that numbers aren't what they look like. By default, a number is treated as a double
. A double
and a float
, though they look the same, are not the same. This has already been covered here: strange output in comparison of float with float literal. And I really recommend to read one of the linked articles, this one: "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
Question number 3:
You are right that the returned value is 0 (the first time!), but then you think that instruction is split in two parts, the first of which being a return
, which should cause the second one (the increment) to be skipped. No, it doesn't work like that. The increment is executed in any case. Post increment works like this: make a copy, increase the original, return the copy. Whatever called the post-increment sees the original value, but the increment does take place. And since x
is static
, the value will be kept, so that the next time the function n()
is called, the initial value of x
will be 1. And then 2, 3, and so on.