First, if N
is constant, the compiler computes N+1
at compile time, and generates the same number of instructions for both options. The case of variable-vs-constant comparison is explained well in this Q&A.
When N
is a variable whose value is available only at run-time, a compiler running at an aggressive level of optimization could produce the same code for both comparisons, too.
I ran an experiment with gcc
running at -O3
optimization level, giving it these two code fragments:
scanf("%d%d", &j, &k);
if (j < k+1) {
printf("hello\n");
}
and
scanf("%d%d", &j, &k);
if (j <= k) {
printf("hello\n");
}
I used scanf
to prevent the compiler from optimizing the expression entirely.
Assembly code produced in both cases was identical:
movl -8(%rbp), %eax
cmpl -4(%rbp), %eax
jg LBB0_2
it compared j
to k
, and jumped over the call of printf
(which optimizer replaced with a call to puts
) when j
was greater than k
.