473,406 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Not getting the expected output in this program

AmberJain
884 Expert 512MB
Hello everyone,
Newbie here, PLZ HELP.......

This is what I coded (it's very very simple, still I'm facing problem with this code) --------->
__________________________________________________ _______________
Expand|Select|Wrap|Line Numbers
  1. #include<conio.h>
  2. #include<stdio.h>
  3. int main()
  4. {
  5. int i=0;
  6. int j=1;
  7. clrscr();
  8. printf("\n %d",i++ && ++j);
  9. printf("\n %d %d",i,j);
  10. getch();
  11. return(0);
  12. }
__________________________________________________ _______________
**************
**OUTPUT**
**************
0
1 1
__________________________________________________ _______________
I'm using Borland Turbo C++ 3.0.
I expect the code
printf("\n %d",i++ && ++ j);
to increment j by 1 and output 0 and then increment i by 1.

Now i becomes 1 and j becomes 2.
Now when the code below is executed
printf("\n %d %d",i,j);
I expect now that the code to print value of i and j as 1 and 2, but I get output as
1 1.

Where am I wrong, Please guide me.
__________________________________________________ _______________
THANKS TO EVERYONE IN ADVANCE...............
Mar 2 '08 #1
11 1720
scruggsy
147 100+
Hello everyone,
Newbie here, PLZ HELP.......

This is what I coded (it's very very simple, still I'm facing problem with this code) --------->
__________________________________________________ _______________
#include<conio.h>
#include<stdio.h>
int main()
{
int i=0;
int j=1;
clrscr();
printf("\n %d",i++ && ++j);
printf("\n %d %d",i,j);
getch();
return(0);
}
__________________________________________________ _______________
**************
**OUTPUT**
**************
0
1 1
__________________________________________________ _______________
I'm using Borland Turbo C++ 3.0.
I expect the code
printf("\n %d",i++ && ++ j);
to increment j by 1 and output 0 and then increment i by 1.

Now i becomes 1 and j becomes 2.
Now when the code below is executed
printf("\n %d %d",i,j);
I expect now that the code to print value of i and j as 1 and 2, but I get output as
1 1.

Where am I wrong, Please guide me.
__________________________________________________ _______________
THANKS TO EVERYONE IN ADVANCE...............
Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

There's your explanation, but what's more important to realize is that:
- mixing boolean expressions inside function calls is generally a bad idea, and
- using unary operators within more complex statements is also generally a bad idea.
Both will often lead to unexpected results and hard-to-read code.
Mar 2 '08 #2
AmberJain
884 Expert 512MB
Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

There's your explanation, but what's more important to realize is that:
- mixing boolean expressions inside function calls is generally a bad idea, and
- using unary operators within more complex statements is also generally a bad idea.
Both will often lead to unexpected results and hard-to-read code.
THANKS
That's what I was lokking for..........
I knew about SHORT-CIRCUIT evaluation, but I didn't knew that I will face it here.
Please tell me one more thing. Does the term "SHORT-CIRCUIT evaluation" is technical terminology in C or it's just some random name for this phenomenon?

ONCE AGAIN, THANK YOU VERY MUCH......
Mar 3 '08 #3
AmberJain
884 Expert 512MB
Short-circuit evaluation causes the problem. Short-circuit evaluation means as soon as the result of an expression is known, the rest of the expression is not evaluated.
In any condition a && b, if a is false then the expression cannot be true regardless of the value of b. So the rest of the expression is skipped because we know the answer already.
When you do i++ && ++j, i starts at zero and because you used the postfix increment operator, i is not incremented until the semicolon. 0 = false, thus the rest of the statement incrementing j is never executed.

There's your explanation, but what's more important to realize is that:
- mixing boolean expressions inside function calls is generally a bad idea, and
- using unary operators within more complex statements is also generally a bad idea.
Both will often lead to unexpected results and hard-to-read code.
__________________________________________________ _______________
HELP, newbie here--------->

Still I am confused......
As you said, the operand on the right side of logical operator (&&) is not evaluated if left operand evaluates to FALSE. But according to priority rules of C language, UNARY operators (for example ++ in this question) have a higher priority then binary operators.
Therefore regardless of value of expression on left of operator &&, first of all i++ and ++j must be evaluated separately as they have a higher priority than && operator.

I know I'm wrong somewhere (in basic concept), so please guide me.........

THANKS TO EVERYONE IN ADVANCE.........
__________________________________________________ _______________
Mar 4 '08 #4
AmberJain
884 Expert 512MB
__________________________________________________ _______________
HELP, newbie here--------->

Still I am confused......
As you said, the operand on the right side of logical operator (&&) is not evaluated if left operand evaluates to FALSE. But according to priority rules of C language, UNARY operators (for example ++ in this question) have a higher priority then binary operators.
Therefore regardless of value of expression on left of operator &&, first of all i++ and ++j must be evaluated separately as they have a higher priority than && operator.

I know I'm wrong somewhere (in basic concept), so please guide me.........

THANKS TO EVERYONE IN ADVANCE.........
__________________________________________________ _______________
Somebody PLZ HELP IN THIS MATTER.......................
Mar 5 '08 #5
weaknessforcats
9,208 Expert Mod 8TB
I expect your compiler is evaluating i++, which makes i 1 but used 0 for the expression and then does the && and sees that the expression can never be true and stops evaluating.

That means you do not put calculations in an expression such that unless the expression is completely evaluated you get the wrong answer.

In this case, do the incrementing before you get to the expression.

This is a classic C pitfall.
Mar 5 '08 #6
AmberJain
884 Expert 512MB
I expect your compiler is evaluating i++, which makes i 1 but used 0 for the expression and then does the && and sees that the expression can never be true and stops evaluating.

That means you do not put calculations in an expression such that unless the expression is completely evaluated you get the wrong answer.

In this case, do the incrementing before you get to the expression.

This is a classic C pitfall.
OK, I got what you meant to tell.

But, I am stucked now at the point that increment/decrement (post or pre) operators have a higher priority than logical operators.
Furthermore, both type of operators have a Left to Right associativity (as far as I know).
Therefore before compiler goes to execute &&, it must first execute POST and PRE ++ operators due to their higher priority. But the compiler is responding differently. So please guide me.


I may be wrong somewhere in above statement of mine. If so, then please forgive me and guide me.

THANKS..................
Mar 6 '08 #7
weaknessforcats
9,208 Expert Mod 8TB
The compiler did that. It evaluated the i++ first.

Then it associated the left (i) in the && evulation and found that with i 0, the expression could never be true. No point in going any further. Wastes time.

You are assuming that all of the operands in the expression have to be evaluated before the expression itself can be evaluated. This is not required to happen. Some compilers may do as you think while others do not.
Mar 6 '08 #8
MACKTEK
40
You know it makes sense that it "should" increment, but it does not.
I can "guess" as to why -- "compiler optimization"
Here is a link for rules of precendence:
After the table (in link) it says
In some circumstances, the order in which things happen is not defined.
In otherwords, if a certain behavior is not MANDATED then the compiler will have ambiguous behavior.

In your case:
The compiler is trying to optimize for speed.

It sees: i++ && ++j
Using the rules of precedence it should evaluate i++ FIRST.
Now think about that. Its saying do i++ First, but its pretty clear, the actual Post-Increment only adds AFTER the ";" has been reached.

So, anyway in the case of i++ && ++j
The compiler sees &&... it knows that that to optimize for speed, all it has to do is find 1 case where ANYTHING on the left evaluates to zero... if that occurs it ignores the rest of the expression and returns a 0.

This is called Short Circuit Evaluation:

Should it occur if the compiler was "really following precedence rules", probably not.

But its omptimizing for speed, and ignoring the precedence.

Now that you know these things can occur. It is best not to have any operations that alter variables during the evaluation of logical operators especially where such ops can be cut short by compiler optimizations.
Mar 6 '08 #9
AmberJain
884 Expert 512MB
The compiler did that. It evaluated the i++ first.

Then it associated the left (i) in the && evulation and found that with i 0, the expression could never be true. No point in going any further. Wastes time.

You are assuming that all of the operands in the expression have to be evaluated before the expression itself can be evaluated. This is not required to happen. Some compilers may do as you think while others do not.
Thank you WEAKNESSFORCATS....
Mar 8 '08 #10
AmberJain
884 Expert 512MB
You know it makes sense that it "should" increment, but it does not.
I can "guess" as to why -- "compiler optimization"
Here is a link for rules of precendence:
After the table (in link) it says
In otherwords, if a certain behavior is not MANDATED then the compiler will have ambiguous behavior.

In your case:
The compiler is trying to optimize for speed.

It sees: i++ && ++j
Using the rules of precedence it should evaluate i++ FIRST.
Now think about that. Its saying do i++ First, but its pretty clear, the actual Post-Increment only adds AFTER the ";" has been reached.

So, anyway in the case of i++ && ++j
The compiler sees &&... it knows that that to optimize for speed, all it has to do is find 1 case where ANYTHING on the left evaluates to zero... if that occurs it ignores the rest of the expression and returns a 0.

This is called Short Circuit Evaluation:

Should it occur if the compiler was "really following precedence rules", probably not.

But its omptimizing for speed, and ignoring the precedence.

Now that you know these things can occur. It is best not to have any operations that alter variables during the evaluation of logical operators especially where such ops can be cut short by compiler optimizations.
THANK YOU VERY MUCH............
This is what I was searching for. It is really a nice explanation for my problem.
THANK YOU AGAIN FOR HELPING ME OUT.
Mar 8 '08 #11
MACKTEK
40
Your are welcome. Scrugsy actually explained it all, I just interpreted!
Mar 9 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Seagull Manager | last post by:
Running Apache 1.3, PHP 4.3, and WinXP, configured acc. to instructions on apache manual and php manual (as far as I can see), but getting "internal server error" in browser... log says "Premature...
0
by: Terence | last post by:
The XML (expat) extension to PHP contains specific functions for accessing detailed error information when an error occurs parsing an XML packet. All be it convoluted, even the XSLT (Sablotron)...
6
by: Christian Convey | last post by:
Hello, I've got a program that (ideally) perpetually monitors sys.stdin for lines of text. As soon as a line comes in, my program takes some action. The problem is, it seems like a very large...
3
by: sp | last post by:
hai i have got 1. an xml file 2. an xsl file and my xsl file filters the xml based on attribute value and the output i receive is in the ordinary format
25
by: altemurbugra | last post by:
Hi is it possible to make search on for example on google without api with a list of words 1- there is word list 2- the script will take the words from the list by turn 3-it iwll make the search...
7
by: RSH | last post by:
This is probably a very simple question but... How do I get the instantiated name of an object from within the class? Example: Sub main Dim c1 as new TestClass() c1.PrintName()
10
by: hpbrothers | last post by:
#include<iostream.h> #include<conio.h> void main() { int a,b,i,j,k=0,fg=0; for(i=0;i<5;i++) { cout<<"enter no."; cin>>a;}
2
by: hpbrothers | last post by:
#include<iostream.h> void main() { char mstr; char cstr; int c=1,k=0,i,j; cout<<"enter main string"; cin.getline(mstr,100); for(i=0;mstr!='\0';i++) {
7
by: alphasahoo | last post by:
Hi I am working on a program which writes the output a SQL select statements from number of source tables first to a load matrix and then writes to a load.dat file. But while writing to the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.