?
Solved

Conditional Confusion

Posted on 2003-02-23
30
Medium Priority
?
241 Views
Last Modified: 2010-04-15
Hi EveryBody
 I juz came across this interesting piece of code , juz
 thought of sharing it with you all
 
 K=1;
 K=K?K++:0;
 printf("%d",K);            
                      I  expected 2 to get printed but
 the OUTPUT is 1 .However
 
 K=1;
 K=1?K++:0;       // K replace by 1 ,thats the only change
 printf("%d",K)  // this piece of code prints 2 as
 output ..................
 
                        assignment operator anyway
 has got a lower precedence ( level 15 )  when compared to ternary ( level 14) .  my  understanding is that  both  pieces of code should give the same output ... But  thats not so . something has  been overlooked ...
Can anyone Help ?

-Hari { SweetPoison }
0
Comment
Question by:SweetPoison
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 7
  • 5
  • +6
30 Comments
 
LVL 8

Expert Comment

by:akshayxx
ID: 8006508
thanks for sharing .. listening
0
 

Expert Comment

by:chirilabogdan
ID: 8006825
because first the compiled do K=K, and after that K++;

try to  K=K?++K:0;

:))
0
 
LVL 2

Expert Comment

by:honey_hamster
ID: 8012115
I'm not a stickler for order-of-operations - I can never
remember them, so I use brackets.

Anyway, I think the following may be valid:

In your first case, the compiler does the following:
1) checks k to see whether you want the TRUE or FALSE expression
2) gets the left-hand value of k++ (which is 1)
3) increments k, i.e. k becomes 2 (a temporary side-affect)
4) assigns the left-hand value from 2) to k, i.e. k = 1

In other words, the assignment (=) happens last.

The 2nd case is equivalent to k = k++;  That's because
the compiler can tell at compile-time that the the
condition is always true.  And of course, k = k++; is
equivalent to k = k; k = k + 1;

Maybe somebody more into very strict 'C' rules can
explain this in more official and technical terms.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 8

Expert Comment

by:akshayxx
ID: 8013146
i dont have indepth knowledge of assembly .. but some of u might get the assembler code from this c code and see-through the steps.
i saw it it was about 20 lines .. so not much big by any standards
0
 
LVL 1

Expert Comment

by:Gula
ID: 8013475
It is interesting... I don't know why could this happen, so I tried to run your code..
I tried both of them on MS Visual C++, both give same result - 1... with ++K both give same result again - 2...
am I missing something???
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 8014458
This is the problem with using post/pre increment in statements!
Now change your code to use preincrement....It will output 2!!

What is happening with your first code is that:
1. The statement will be split up as follows:
   if (K == 0) K = 0;
   else
   {
      K++;
      K = 1;
   }
 K++ will be replaced by 1 at the compile time itself.  
 K will be incremented.
 The assignment statement is executed.

That's the reason you are getting 1 as o/p even after K++!

Hope I am clear....:-)

-Narendra
0
 
LVL 12

Accepted Solution

by:
rajeev_devin earned 80 total points
ID: 8014634
Let us analize the code fragment
K=1;
(K=K?K++:0);

1. K is assigned 1.
2. (a) Since ++ operator has higher precedence than = , K
       will be incremented to 2. But for this operation
       its old value 1 will be used.
   (b) Next K will assigned the value 1 (old value) to
       itself, thus overriding the old operation value.

Thus the value 1 is printed.

The another code that you have given also prints the value 1, I have tested that code fragment also. You test it once more.

K=1;
K=1?K++:0;
printf("%d",K)int K;

The compiler that i am using is VC++, console mode project.

Hope this may help you.
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8014771
>>>The another code that you have given also prints the value 1, I have tested that code fragment also. You test it once more.

gives me 2.. i checked it ..  with gcc
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8014774
so compilers doing the trick
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 8014890
SweetPoison,

Do you want more explanation!?

-Narendra
0
 
LVL 1

Expert Comment

by:Gula
ID: 8016985
SweetPoison, what compiler do you use?
same to akshayxx and rajeev_devin
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8022438
gcc 3.2
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8022442
while on windows . i use gcc 2.95 .. rarely VC
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 8022895
The problem is not with the compilers! It's the "undefined" behaviour of increment(post/pre) operator in expressions. Every compiler can implement this in its own way. ANSI doesn't say anything about this!:-))
This sort of usage will definitely introduce hard to find bugs. It's better to keep the increment seperate and make the expressions as simple as possible. By doing this you will be writing extra statements. But, for the computer, both are same. The advantage is that, it's easy to debug and will be easier to maintain.

-Narendra
0
 

Author Comment

by:SweetPoison
ID: 8032349
Thanx everybody for ur efforts , I am using a TC ++ 3.0 environment .
Actually some of my friendz let me know that the problem is caused due to the modification of the  variable k twice within the sequence point causes an undefined behaviour
1)K=K..... ( first)
2)...?k++  ( second)

There are 4 operators that are deemed as sequence points ... [ thats what Kanetkar's Test your C skills tells ]
But i am myself in a state of confusion ..Anyway all ur comments have been of immense use ....THanx
- hari[ sweetpoison]
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 8032466
So, you are still confused!?:-))
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8101735
I wonder how you got different outputs in the first place. Mr. rajeev_devin has perfectly explained the reason for the first output. And he is correct - the second block of code will also give the same output. I tried it on Turbo C++ 3.0 and it did. And the same reasoning applies for it too. Check your output once more.

Mayank.
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8102326
mayank:
It has already been pointed out that , the code that he has mentioned is giving different answers with different compilers.
and with such a straight forward piece of code, he was pretty much sure of his output , thats why he posted the source code..
so it doesnt sound good when u say "check your output once more"

I myself has checked the code and it does behaves the way  he has claimed..
 Please try to follow up the discussion before making any  useless comments

look here  i didnt even have to change his posted code ..



hanoi@AKSHAY[21:34]~/test$ cat poison.c
#include <stdio.h>
main(){
int K;

K=1;
K=K?K++:0;
printf("%d\n",K);
//  I  expected 2 to get printed but the OUTPUT is 1 .However

K=1;
K=1?K++:0;       // K replace by 1 ,thats the only change
printf("%d\n",K);  // this piece of code prints 2 as

}
hanoi@AKSHAY[21:34]~/test$ gcc poison.c
hanoi@AKSHAY[21:34]~/test$ ./a.exe
1
2
hanoi@AKSHAY[21:34]~/test$


0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8102329
mayank:
It has already been pointed out that , the code that he has mentioned is giving different answers with different compilers.
and with such a straight forward piece of code, he was pretty much sure of his output , thats why he posted the source code..
so it doesnt sound good when u say "check your output once more"

I myself has checked the code and it does behaves the way  he has claimed..
 Please try to follow up the discussion before making any  useless comments

look here  i didnt even have to change his posted code ..



hanoi@AKSHAY[21:34]~/test$ cat poison.c
#include <stdio.h>
main(){
int K;

K=1;
K=K?K++:0;
printf("%d\n",K);
//  I  expected 2 to get printed but the OUTPUT is 1 .However

K=1;
K=1?K++:0;       // K replace by 1 ,thats the only change
printf("%d\n",K);  // this piece of code prints 2 as

}
hanoi@AKSHAY[21:34]~/test$ gcc poison.c
hanoi@AKSHAY[21:34]~/test$ ./a.exe
1
2
hanoi@AKSHAY[21:34]~/test$


0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8117547
Hi Akshay!

I didn't everybody else's comments since there were so many of them, but SweetPoison's comments say that he's using TC ++ 3.0, which is exactly the environment on which I executed the program and got an output different from what he got. That's why I said so.

Mayank.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8117550
Hi Akshay!

I didn't read everybody else's comments since there were so many of them, but SweetPoison's comments say that he's using TC ++ 3.0, which is exactly the environment on which I executed the program and got an output different from what he got. That's why I said so.

Mayank.
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8117627
Mayank Eagle
in that comment he said ...
>>>Actually some of my friendz let me know that the problem
so its not necessary that he is also using TC 3.0

 ANd what do u have to say about the output i have shown..

also one tip for you .. i have observed that these days u r browsing through all the questions and making comments ... despite the fact that asker hasnt shown activity for quite long .. and the question already has lots of comments ..
so its worthless to comment on already heavily commented question.. and which is as good as dead ...
unless u have something very new to tell..
also .. such kind of inactivity from asker .. EE tries to close questions which hasnt shown activity in last 21 days .. but if we keep commenting on such 'dead questions' then they get new life .. even if the user isnt responding ..
i hope u got the point ..
 
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8117850
My dear friend Akskay,

SweetPoison has explicitly written: I am using a TC ++ 3.0 environment

Anyways, it just that I had a different output on the same environment, so I commented. It is a problme when people are unspecific about their questions.

Stop bothering yourself with everybody's comments, man! And yeah! I usually only post answers to questions asked in the previous one week - not to older ones.

Got work to do.

Mayank.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8117855
As for your output, well.... maybe that's why he's confused too! Its really amazing.
0
 
LVL 8

Expert Comment

by:ssnkumar
ID: 8118527
Why you ppl are quarreling when questioner himself is keeping silent!?:-))
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8118781
Oh, leave it aside, yaar. For everything else.... its still a good question.

Ever tried:

int i = 5 ;
printf ( "%d", i ++ ) ;
printf ( "%d", ++ i ) ;

i = 5 ;
printf ( "%d%d", i ++, ++ i ) ;

????

Stacks come into the picture for explaining that.

Mayank.
0
 
LVL 8

Expert Comment

by:akshayxx
ID: 8119122
mayank:
thats a typical c question asked in interviews and screening tests, i also put up similar questions when i prepared papers for recruitment at our company.

the only thing that annoyed me is that most of ur comments werent adding any good to the discussion.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8544842
How about rating it now?
0
 
LVL 20

Expert Comment

by:jmcg
ID: 10018087
Nothing has happened on this question in over 7 months. It's time for cleanup!

My recommendation, which I will post in the Cleanup topic area, is to
accept answer by rajeev_devin (acknowledging other good responses, but too few points...).

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jmcg
EE Cleanup Volunteer
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question