# If and summation: why do I have the index of the summation in the final result?

Consider the following code:

Sum[If[b != 0, a[m], 0], {m, 1, 4}]

(* 4 If[b != 0, a[m], 0] *)


Why does it return me a[m]? m is the index of the summation, it shouldn't appear in the result.

Here I expect to have:

If[b != 0, a, 0]+If[b != 0, a, 0]+If[b != 0, a, 0]+If[b != 0, a, 0]


I don't understand this behavior

(my example here is to understand this behavior, my specific problem is more complicated but the problem is the same as this one showed here).

This works:

Sum[If[b != 0, a[m] // Evaluate, 0], {m, 1, 4}]


From the documentation:

If evaluates only the argument determined by the value of the condition.



You can use Evaluate to override HoldFirst etc. attributes of built-in functions.

Sum[If[b =!= 0, a[m], 0], {m, 1, 4}]


which returns

a + a + a + a


The difference between the != and =!= operators is very important here. Because the truth value of b != 0 could not be determined, therefore the If[] expressions were returned unevaluated.

I suggest moving the If[] expression out of the summation. That is use

If[b =!= 0, Sum[a[m], {m, 1, 4}], 0]


instead. This simplifies the code and makes it easier to understand.