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.
Concerning the following usage, i'm confused how --i evaluates to true and what determines when the loop exits:
while (--i) {
k = p[i];
p[i] = p[j = random() % B];
p[j] = k;
}
if as I understand it the -- prefix is decrementing the value of i before it begins the loop, are we then evaluating true=value > 1 and false=0 and thus the loop exits when the value reaches 0? Perhaps I've answered my own question, but if anyone could enlighten me on this. Also, how would this loop behave if the decrement operator was a suffix?
Yes, prefix decrement will decrement the variable, then the returned value (the result) from the expression is used for the condition.
The loop terminates when i becomes 1 (and it decremented to 0, the returned value of the condition).
As you have defined your code i can say that it totally depends on the value of i.
if the value of i=0 initially then it will go in infinite loop because --i will become -1 which will be true condition for the while loop.
so if the value of i is other than 0 (may be positive or negative) then it will always true but when it will become 0 the loop will terminate
and for prefix & suffix ... u should remember that in (-- variable) or (++ variable) case the variable will be incremented or decremented first then checked but in (variable --) or (variable ++) case the variable will be incremented or decremented later but checked first
Related
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.
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 found some code similar to this (not exactly just the weird logic has been replicated) :
for(int counter = 0 ; counter < array.length() ; counter ++ ) {
array.removeObjectAtIndex(i);
counter -- ;
}
Is this bad code ? What should one do assuming there is no primitive method to empty the whole array or that we need to do some extra cleanup after removing each element ?
If you go from the top down, you won't need counter--, and it's more efficient because it won't have to shift the array elements above each time removeObjectAtIndex is called.
Interfering with a loop counter inside the loop body is never a good idea.
Despite not knowing what array is, a better way would be to continuously remove the array head until the array is empty.
int length = array.length();
for(int counter = 0 ; counter < length ; counter++ )
{
array.removeObjectAtIndex(0);
}
Well, the first thing to note here is that at the end of every loop there's a counter++ and a counter--. Effectively canceling each other out.
I suspect a junior programmer was taught that for loops require the format
for(int i=0;i<len;i++) {/*code*/}
Going forth on that logic, due to the length for the array shifting by one with each pass in the loop, he required counter to get decremented as well (as to not generate fake results).
for(int c=0;c<a.length();c++){a.remove(i);c--;}
If you remove c-- from this implementation, you would remove only half the indexes. Counter would go up as length would go down, effectively meeting half way.
Now a different implementation that feels less rigid
for(;array.length()>0;){array.removeObjectAtIndex(i);}
// also this
for(;array.length();array.removeObjectAtIndex(i));
OP mentioned .length() might be inefficient, so:
for(int len=array.length();len--;array.removeObjectAtIndex(i));
For's are incredibly powerful, I personally find them highly underused in some situations.
I agree with acraig5075's comment about interfering with a loop counter inside the loop body is bad habbit
i think bottom up approach as below code will work fine
for(int counter = array.length - 1; counter >= 0; counter--)
{
array.removeObjectAtIndex(counter);
}
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.
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.
#include<stdio.h>
void main()
{
int i = 10;
i=!i>14;
printf("i=%d",i);
}
I get the output : i=0
I get the same output even when I change the value of i to any other integer.
What does this code do?
Please explain
This line
i=!i>14;
is parenthesized (implicitly)
i= (!i) > 14;
Since the result of a ! is always either 0 (if i != 0) or 1 (if i == 0), the result is always smaller than 14.
Your printf call
printf("i=%d");
misses its second argument (thanks #DSM for spotting it), that invokes undefined behaviour, since each conversion specifier must have a corresponding argument of the correct type.
Also, your printf call just specifies a format but is missing i as argument.
This statement: i = !i > 14 assigns to the variable i the result of the expression: !i > 14.
(!i) > 14 is false because !i is zero for any non-zero number, i.e. 0 > 14. Since false is represented in C by 0, i gets the value 0.
Also, your printf call doesn't have a matching argument for the %d in the format string. The printf should be: printf(i=%d\n", i);
Just to complement the other answers:
There is an error in this line:
printf("i=%d");
It should be:
printf("i=%d",i);
Due to precedence rules, that line reads as:
i = (!i)>14;
So, i is 10, which, for the ! operator, is true; ! negate this, giving false, i.e. 0, so what you get is 0>14, which is obviously false, i.e. 0.
I think you wanted this
i=!(i>14);
The logic you wrote resolves from left to right completely, first not(i) then it's result is tested against 14 for greater than.
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 12 years ago.
iS THIS TRUE OR FALSE ? explain?
i++ = ++i
No, it isn't. Either true OR false.
The problem is that C/C++ don't define when ++ happens within this expression.
So you have several possibilities:
Add 1 to i for the ++i then store that back in i, then add again for thei++`.
add 1 to i for the i++ and save thje result for later; add 1 to i for the ++i assign it to i and then put the saved value of i++ into i.
Add 1 to i for the i++ and then assign the result of ++i on top of it.
It gets even better when you consider, say, i = ++i++;
(See the link in the comments. The technical issue with whether there is a "sequence point" there, at which point all side effects should be resolved. In this assignment, there's not one.)
It depends what it is you're actually getting at:
If you meant does the following expression evaluate to true:
i++ == ++i
then it's undefined behaviour because i is modified twice between sequence points.
If you meant:
do i++; and ++i; do the same thing then the answer is sort of -- they both increment i. Where they differ however is if they are part of a larger statement, do they use the value before or after the increment.
In practice this means that i++ might possibly involve making a copy internally, in order to store the value before the increment, whilst ++i doesn't need to make such a copy.
If you were asking about i++ = ++i; as a statement on its own then it's not a valid statement for a more fundamental problem: the i++ cannot be the lefthand side of an assignment because of the "temporary" nature of its value.
See this link and this one for more discussion etc.
Just in case you don't know the difference between pre-increment and post-increment and you just formulated the question unintelligible:
i = 7;
printf("%d\n", i); // precondition: result 7
printf("%d\n", ++i); // PRE-INCREMENT: result 8 !!!
printf("%d\n", i); // postcondition: result 8
i = 7;
printf("%d\n", i); // precondition: result 7
printf("%d\n", i++); // POST-INCREMENT: result 7 !!!
printf("%d\n", i); // postcondition: result 8