Describing the following code [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I've got a question regarding an assignment i've been given.
-There are two integeras, a and b, which has the value of -1 and 1 respectively.
What's the value of a and b after running the following code and WHY.
if(!++a)
b+=a++;
When i run this code i'm getting the values 1 and 1. I can not really figure out WHY though... Im getting quite confused over the if statement, could anyone explain this for a beginner trying to learn C?

Your code is equivalent to this one:
int a = -1;
int b = 1;
a += 1;
if (a == 0) {
b += a;
a += 1;
}
You should see why both variables end up as 1 here. Now try to figure out why these codes are equivalent.

if (!++a)
First of all, if (a) is identical to if (a != 0). Weird, but true. Zero means false, any other number means true.
Saying if (!a) inverts that meaning.
++a increments a and returns the new value. (Unlike a++, which increments a but returns the old value, not the new one.)
Putting all that together, this says "increment a and test whether the answer is zero". If a = -1, then this is indeed true.
Usually people would write if (...) {do stuff}, but if the "do stuff" part is only one statement, you can leave out the brackets. We've already established that the condition is true in this case, so the "b+=a++" line is run.
If we put some spaces on that, we have
b += (a++);
So, increment a again, but before that, add it's (old) value to b.

++a gives you the value after increment, so you get 0 which means false. The ! operator makes it true.
Then you basically have
b = b + a;
a++;
So b remains 1 and a gets another increment and ends up at 1 too.
The main concept here is the difference between a++ and ++a. If you use a++ you will first get the value of a and then the value is incremented whereas for ++a the value is first incremented and then returned.

Initially a= -1 when your code will enter if (!++a) and it is pre increment first increment of a will happen so a will become 0 and !0 is 1 and it will enter in the if block.
now b+=a++;
here a++ is post increment so you can devide this statement in two parts.
first b+=a; b+=0 so b will remain 1.
second a++; a will become 1.

Related

Getting wrong output for a++ +b according to lexical analysis when the program is printed along with a+++b [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I wrote the following C program to find the output for a+++b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
}
And I'm getting the output as 7 which is correct according to lexical analysis.
Apart from that I wrote a separate program to find the output for a++ +b
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a++ + b);
}
For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)
But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs
#include<stdio.h>
int main()
{
int a=5, b=2;
printf("%d",a+++b);
printf("\n%d",a++ + b);
}
The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong).
Can anyone point out the error in the third program?
a++ is post-fix increment. It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).
So after the first printf() the value of a is 6.
So what do you now expect from the second printf?
Operators like post-fix ++ are expressions (have a value) and instructions (have an effect). They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.
(*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever.
They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!
The issue here isn't the space in the second statement, it's the fact you have two of them. After the first statement (to be exact, after a++ is called), the value of a is incremented and is now 6. So a++ + b will clearly return 8. If you omit the first printf call and just call the second one, you'll get 7 as you expect.

How two individual operators are parsed/evaluated while written together? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
What's really happening behind?
int a=10,b=5,c=3;
b!=!a;
c=!!a;
Why the values of b and c are 5 and 1 respectively?
b is 5 because you've assigned it that value and never changed it, since
b!=!a;
...is just a condition that you don't do anything with, not any form of assignment.
c is 1 because a is 10 and !10 is 0, and !0 is 1, thus !!a is 1 (a is 10).
You already have got the answer to your question, but just to have a deeper look into why it happens that way, let me add my two cents here.
An expression like
b!=!a;
is same as
b != !a;
because of the maximal munch rule used in the translation phase. Basically, this says that the longest possible token should be selected from the input while creating a construct (obviously, valid/ meaningful).
Following this principle the ! and = are considered together to form the perfectly valid operator != and the expression is parsed like
b != !a;
over
b ! = !a; //or anything else.
That is why, there is no assignment, as you might have thought.
That said, ! is an unary operator, which does not change the value of the operand. So, taken together, your code is essentially same as
int a=10,b=5,c=3;
c=!!a; //double negation
so, a and b are unchanged, and c is 1 (because !!10 == !0 == 1 )

Pre Increment & Post Increment [duplicate]

This question already has answers here:
Is the output of printf ("%d %d", c++, c); also undefined?
(6 answers)
Determining subroutine argument evaluation order [duplicate]
(2 answers)
Closed 8 years ago.
Today I revisited Pre Increment and Post Increment.
Basic definitions I know.
Pre Increment - Increments the Value and returns the value.
Post Increment - Increments the Value and returns the value prior to increment.
But Doing some combinations of them i am stumped.
Using a basic C program, here is what I tested.
With i =0 initially.
1st Test
printf("%d %d",++i,++i);
Ouput:
2 2
I Expected:
1 2
2nd Test
printf("%d %d",i++,i++);
Ouput:
1 0
I Expected:
0 1
3rd Test
printf("%d %d",i++,++i);
Ouput:
1 2
I Expected:
0 2
4th Test
printf("%d %d",++i,i++);
Ouput:
2 0
I Expected:
1 1
I figured the evaluation might be from the right side or the left side. Maybe from left in case of Pre Increment & Right in case of Post increment. Maybe Pre Increment had a higher priority than Post increment. Some ideas to match the results, but assumption made on one test doesn't explain the other output.
Everything you have is undefined behavior because you are modifying the same variable multiple times between the same pair of sequence points. For example
i = i++;
is undefined as well. There's a deeper discussion here, and there's a nice slideshare that covers this and more "deep C" quirks.
The other issue is the order of evaluation. The arguments are evaluated in an unspecified order, so if you have
f(a(), b(), c());
it can call a, b, and c in any order.
You're mixing undefined behavior and unspecified behavior, so although you could venture a guess to explain why you get the output you do, it's hard to give a satisfactory explanation since it's so random.

using goto keyword in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
# include <stdio.h>
int main()
{
int a=5;
begin:
if(a)
printf("%d\n",a);
a--;
goto begin;
return 0;
}
When a becomes 0 then if condition will not execute then why the output is going to be infinty in this code means
output -
5
4
3
2
1
0
-1
-2
and so on endless
If the program really does print 0 for you then there might be a serious problem with your compiler (or even your machine...). My suspicion is that it doesn't print 0, but your question is really why the program loops infinitely.
This is because the if-body only contains the print statement. So when a reaches 0 it isn't printed but the lines
a--;
goto begin;
are still executed. The machine will obey, go back to begin and the loop continues. The quickest fix is to put braces around all the statements you want executed when a != 0:
if(a){
printf("%d\n",a);
a--;
goto begin;
}
return 0;
This will make the program only loop until a is 0, after which it returns.
But the real problem is: don't use goto (for this)! This is a perfect situation to use a while loop:
while(a--){
printf("%d\n", a);
}
return 0;
(The braces around the while-body are not even strictly necessary here, but just good practice)
Its because after the if the goto statement is again executed and then the value of a has already become other than 0 . Now, again you get the goto statement and therefore if goes on executing and printing negative values.
Look at it this way :-
The statement
printf("%d\n",a);
is executed only when condition in if is true. TRUE here refers to anything not equal to 0 so, the printf is not executed when a is 0, while it executes for any other value. Now, a-- and goto are executed outside if so they are executed again and again making the condition in if true always and negative values are printed infinitely.
Nevertheless,
My question is , why are you using goto?
if a==1 -> Evaluates to TRUE
if a==0 -> Evaluates to FALSE
if a==-1 -> Evaluates to TRUE
etc.
Therefore it will display numbers in descending order, except 0 which will not display.

warning: suggest parentheses around assignment used as truth value [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this code and there is something I do not understand
When I compile the following code:
#include <stdio.h>
#include <stdlib.h>
int main() {
double x=1;
double y=0;
if (x!=y)
{
printf("x!=y\n");
}
if (x=y)
{
printf("x=y\n");
}
return 0;
}
I get get the following warning: warning: suggest parentheses around assignment used as truth value
When I run the programm I get the following output
x!=y
x=y
Why is it printing x=y if if '=' is not to compare but just to put the value there is in y in x.
The compiler is warning you that the result of the expression x = y is used inside a conditional; I mention this even though it does not appear to be related to your actual question because these days, usually it means that there's a typo and the author meant to write == instead.
Regarding the question: since x = y evaluates to y (a double) and y is zero, the result is false because that's what the C standard says should happen. From 6.3.1.2:
When any scalar value is converted to _Bool, the result is 0 if the
value compares equal to 0; otherwise, the result is 1.
So running this code should not print the "equals" message, as indeed it does for me.
if (x!=y) // This tests if x is not the same value as y
{
printf("x!=y\n"); // if x is not the same value as y print this
}
if (x=y) // This assigns x the value of y, the tests the new value of x
{
printf("x=y\n"); // if y was not 0, then print this
}
I think you wanted:
if (x == y) // if x is the same value as y
for your second check
EDIT
After reading your comments I see that you're getting both prints... I'm not sure what compiler you're using, but I can't reproduce your results. Are you sure the code is correctly copied? When I run I only get x!=y as expected as per my explanation.
Run your code with gcc and you'll see it correctly... all I can think of is you're running with some weird non C standard compiler and it's checking the value of x before assigning the y.
You're using the wrong operator: = is an assignment, == is the real comparison (equal). The compiler detects this and warns you just in case this might not be intended (it's far more likely you meant to do a comparison rather than an assignment). This is perfectly valid C (as such it's just a warning, no error). Just to be sure it's intentional, it asks you to add brackets around: if ((x=y)). This won't cause any difference code wise, but it shows that the return value is used on its own and the assignment is just part of it (hard to describe).
Edit:
Both lines are printed due to the assignment:
x!=y evaluates to true - as such the first line is printed.
x=y is an assignment, which is essentially saying that x should take the value of y, which is 0 in this case.
As such the second line shouldn't be written (as 0 evaluates to false), but in general, I'd say it's either a bug or some precision error (this shouldn't happen with a simple assignment of 0, but you never know).
It is an suggestion that perhaps you are making an typo.
Usually, you will have:
if(condition)
In your case the condition is an assignment and hence if always evaluates to true hence the suggestion from compiler.
Daniel Fischer Has answered your question. You are testing to see if x=y. It doesn't, so your first test is true. Then you are assigning y to x, which returns true as it worked and results in outputting the second print statement.
The equality operation is == and = is assignment operator
The correct form is if(x == y) but it will run also it if(x=y)
because in this case, if will first evaluate x=y,and it will assign a value from y to x and after it, the expression will treat as if(x) and it will evaluate then.
and now here if x has 0, then if(x) will treat as false otherwise true.
So, x=y will not get print as output.

Resources