Stackingc
Stackingc

Reputation: 15

C programming conditional operator

So simple but there is one thing that I could not understand.

    #include <stdio.h>
    #include <stdlib.h>

     int main () {

     int n=15, p=10, q=5;
     q=n<p? n++: p++;
     printf ("n=%d p=%d q=%d \n" ,n,p,q);

      return 0;
     }

While using the conditional operator, it checks if(5=15<10) n++ else q++

Answer: n=15 p=11 because the statement is false and q=10 and not 15. why is that? so q=p instead of q=n.

Can anyone explain it to me please?

Upvotes: 0

Views: 242

Answers (6)

user3629249
user3629249

Reputation: 16540

regarding:

q=n<p? n++: p++; 

properly written:

q = (n<p)? n++: p++; 

means that the variable: q will be set to either n or p, depending on if the value in n is less than the value in p or not.

So the initial value in q is meaningless

Upvotes: 0

Prince
Prince

Reputation: 851

Its not that much confusing These are increment statements Pre increnent or post increment. So A++ Means value of A is used first in the expression and then it will increment And ++A Means value of A us increment first then used. Ao in the expression

int n=15, p=10, q=5;
q=n<p? n++: p++;

As n<p is false And then it resembles to

q = p++

It means

q = p

Then p = p+ 1. Hope this will clear the doubt..

Upvotes: 1

ProNOOB
ProNOOB

Reputation: 514

q=n<p? n++: p++;

Means

if (n < p) {
  q = n;
  n = n + 1;
} else {
  q = p;
  p = p + 1;
}

Look at your code this way (this is how compiler sees it):

q = ((n < p) ? n++ : p++);

What you probably want is this:

(q=n)<p? n++: p++;

Compiler sees this as:

q = n;
if (q < p) {
  n = n + 1;
} else {
  p = p + 1;
}

Upvotes: 0

sjsam
sjsam

Reputation: 21965

it checks if(5=15<10) n++ else q++

Not true.

q=n<p? n++: p++;

is an assignment.

The C draft in section 6.5.16.1 p2 says:

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

In your case,it just that the value of the right operand is deduced from the expression n<p? n++: p++.

Also as you have two prefix expressions n++ and p++ the value of n and p before the increment is taken into account depending on the branching.

Upvotes: 3

dernst
dernst

Reputation: 72

The q= is an assignment operator so it is not part of the evaluation.

Your conversion to the if statement should really be

if (n < q) {
    q = n;
    n++; 
} else {
    q = p;
    p++;
}

Upvotes: 1

Achal
Achal

Reputation: 11931

check the conditional operator associativity, its Left to Right .

q=n<p? n++: p++;

first n< p is solved which is false, so result will be p++ so q = p++; // here p value also change but first 10 is assigned to q because of post increment

finally p becomes 11 and q = 10

Upvotes: 2

Related Questions