Question:

C Programming - assigning condition?

by  |  earlier

0 LIKES UnLike

Hi everybody,

I was testing some code to check out outputs and I am a little bit confused on my results.

My test involved:

int a = 0, b = 1, c = -1;

c = a-- && b--;

printf("%d %d %d", a, b, c);

and the result I got was:

a = -1, b = 1, c = 0.

I'm a little bit confused as to why c turned into 0. Also, does the "&&" operation in the assignment of the c variable the same as using it in say, an if statement?

If any one could clarify this for me, that would be great.

Thanks.

 Tags:

   Report

2 ANSWERS


  1. c returned 0 because it evaluated (0 && 1). The && is the AND operator. Its the same if used in an if statement. If A and B are two conditions, the result of (A && B) would be true if and only if (A is true and B is true). The value 0 represents true in binary and the value 1 represents false. so (0 && 1) would give you 0 (false)


  2. c would be 1 if and only if both a and b are non-zero. a, however, is 0, so the antecedent is not true, and c is assigned 0.

    a is still 0 and b is still 1 at the time the && is performed because a-- and b-- are "post-decrements": They return the value a variable has before the decrement (a==0, b==1), and then decrement the value and assign that value back (a=-1, b=0).

    Edit: Shaik is wrong. I have never heard of any system that used 0 for true. In C, 0 is false, and anything not 0 is true.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.