Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • Last Modified:

Conditional Confusion

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
SweetPoison
Asked:
SweetPoison
  • 10
  • 7
  • 5
  • +6
1 Solution
 
akshayxxCommented:
thanks for sharing .. listening
0
 
chirilabogdanCommented:
because first the compiled do K=K, and after that K++;

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

:))
0
 
honey_hamsterCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
akshayxxCommented:
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
 
GulaCommented:
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
 
ssnkumarCommented:
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
 
rajeev_devinCommented:
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
 
akshayxxCommented:
>>>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
 
akshayxxCommented:
so compilers doing the trick
0
 
ssnkumarCommented:
SweetPoison,

Do you want more explanation!?

-Narendra
0
 
GulaCommented:
SweetPoison, what compiler do you use?
same to akshayxx and rajeev_devin
0
 
akshayxxCommented:
gcc 3.2
0
 
akshayxxCommented:
while on windows . i use gcc 2.95 .. rarely VC
0
 
ssnkumarCommented:
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
 
SweetPoisonAuthor Commented:
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
 
ssnkumarCommented:
So, you are still confused!?:-))
0
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
akshayxxCommented:
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
 
akshayxxCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
akshayxxCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
As for your output, well.... maybe that's why he's confused too! Its really amazing.
0
 
ssnkumarCommented:
Why you ppl are quarreling when questioner himself is keeping silent!?:-))
0
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
akshayxxCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
How about rating it now?
0
 
jmcgOwnerCommented:
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!

  • 10
  • 7
  • 5
  • +6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now