#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

Recommended Answers

All 9 Replies

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

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??

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?

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?

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.

I agree that the comma simply separates expressions

@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");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.