-1
#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 by saurabh.mehta.33234

4
Contributors
9
Replies
30
Views
4 Years
Discussion Span
Last Post by Moschops
0

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 by Moschops

0

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?

-1

@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 by saurabh.mehta.33234

0

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 by Moschops

-1

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 by saurabh.mehta.33234

1

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 by Moschops

-1

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

1

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 by Moschops

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.