1

I came through this code snippet while I was referring to C++ multiple-choice questions. Previously I used only && or || for combining multiple conditions, but this code uses ',':

using namespace std;

int main()
{
   int i;
   for (i = 0; i < 0, 5; i++)
       printf("%d ", i);
   return 0;
}

Formally, the answer for this one is an infinite loop. What is the working of this snippet? How are the conditions getting evaluated?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

2

You have a comma operator in the condition of your for loop. The comma operator evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). The comma operator also has the lowest precedence of all C/C++ operators, meaning it's always the last one to bind to an expression.

So the condition in your for loop is equivalent to:

(i < 0), 5

The result of this expression is always 5, which is not 0 (false). Hence the condition is always true.

If you leave loop running for long enough eventually i, which is a signed integer, will overflow. This results in undefined behaviour (thanks @Jarod42).

jignatius
  • 6,304
  • 2
  • 15
  • 30
  • Or in other words, Since the for loop conditional check uses the comma operator it will allows evaluate ```(i <0 ) ``` first then ```5``` second resulting in the condition always being true because the expression ```5``` is always true, therefore infinite loop. – Michael Apr 24 '20 at 05:21
  • 2
    @Mike: not infinite loop, UB with signed overflow of `i`. – Jarod42 Apr 24 '20 at 06:27
  • @Jarod42 then ans should be undefined behaviour-depends on compiler .. right?? – Gyanesh Sharma Apr 24 '20 at 09:28
  • @gyaneshsharma: your snippet exhibits UB. – Jarod42 Apr 24 '20 at 09:37
0

In function 'int main()':

10:16: warning: left operand of comma operator has no effect [-Wunused-value]

Run your code here and read the warnings.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
abdulrhmanOmran
  • 111
  • 1
  • 7