#include<stdio.h>
void main()
{
int n=5;
if(n==5?printf("Hallo"):printf("Hai"),printf("Bye"));
}

The output of the above code is HalloBye..But I am not able to debug it..I know that ternary has precedence over comma operator but i am stuck at which operand will go with which operator..Can someone please help

Edited 3 Years Ago by saurabh.mehta.33234

The comma operator means n==5?printf("Hallo"):printf("Hai") is evaluated, then printf("Bye") is evaluated. The if statement is doing nothing here.

Edited 3 Years Ago by Moschops

remove the if as it has no effect on the code

the conditional operator ?: gets executed first as it has more precedence over , operator.

may i know wat u want to debug here?

@Moschops thanks for your explaination..but I have a doubt that since the order of evaluation is left to right then according to it ternary should execute first printing Hallo then comma should execute evaluating the expression n==5?printf("Hallo"):printf("Hai") again printing hallo and then lastly Bye..So the output must beHalloHalloByeCan you please explain is this logic correct??

Edited 3 Years Ago by saurabh.mehta.33234

The comma separates two evaluations. The one on the left of the comma is evaluated, then the one on the right.

The one on the left executes first. Here is the complete expression on the left: n==5?printf("Hallo"):printf("Hai"). This prints Hallo

Here is the second evaluation, on the right: printf("Bye") This prints Bye

Why do you think this: n==5?printf("Hallo"):printf("Hai") should be evaluated twice?

Edited 3 Years Ago by Moschops

Why do you think this: n==5?printf("Hallo"):printf("Hai") should be evaluated twice?

One time for the ternary operator coz ternary executes first and second for the comma operator as it will also evaluate the expression on its left which is n==5?printf("Hallo"):printf("Hai") the braces from my point of view must be as
((n==5?printf("Hallo"):printf("Hai")),(printf("Bye"))) is it correct?

Edited 3 Years Ago by saurabh.mehta.33234

second for the comma operator as it will also evaluate the expression

It does not. The comma does not evaluate anything. The comma simply separates expressions.

Edited 3 Years Ago by Moschops

@Moschops Rectifying my mistake as "left side of comma operator will be evaluated first"..So in this case the wouldnt the ternary operator execute again??

Do you understand why in the following code, the first line is only evaluated once?

n==5?printf("Hallo"):printf("Hai");
printf("Bye");

How about this code?

n==5?printf("Hallo"):printf("Hai"); printf("Bye");

Edited 3 Years Ago by Moschops

This question has already been answered. Start a new discussion instead.