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?

4
  • 2
    That's the comma operator. Also, using namespace std isn't C Commented Apr 24, 2020 at 4:26
  • @Spikatrix right i edited that .. mistook it as it came in c mcqs...Btw thankyou! Commented Apr 24, 2020 at 4:36
  • What is the intent of this snippet? What are 'the conditions'? (i between zero and 5?) Commented Apr 24, 2020 at 5:21
  • A canonical question is Multiple conditions in a C 'for' loop. But there must be one from 2008 or 2009. Commented Sep 1, 2022 at 22:55

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@Mike: not infinite loop, UB with signed overflow of i.
@Jarod42 then ans should be undefined behaviour-depends on compiler .. right??
@gyaneshsharma: your snippet exhibits UB.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.