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

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.

Related

Describing the following code [closed]

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.

Implicit type casting in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
please don't burn me if I'm asking a stupid question but I have problems with implicit type casting in complex statements and I want to learn it.
My code segment is;
int a[]={156, 490, 647};
int b[]={218, 789, 461, 750};
int x=2, y=3;
float result;
result = (float) ( a[x] - b[y]) * 0,05 + 50;
printf ("%.2f", result);
What I meant here was "" (647-750) * 0,05 + 50 ""
So the requested output was:
44,85
What I got is:
-0,00
Sorry if I have done a stupid typo, I think I have made the mistake at placing the (float) but I don't know where to put it. I tried many things but couldn't solve it. Thanks..
Change 0,05 to 0.05.
I think you come from a part of the world where , is used as a decimal separator. But C code always uses . as the decimal separator, irrespective of the compilation locale.
The , in your code is the comma operator.
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
So, your expression is evaluated like this:
result = (float) ( a[x] - b[y]) * 0;
And then 05 + 50 is evaluated and thrown away. Or the compiler probably just doesn't bother with it at all and just optimises it away completely.
You can write your assignment statement like this, with no casting:
result = (a[x] - b[y])*0.05 + 50;
When you make this change, the output is as you expect.
Use dot . as decimal seperator instead of comma ,. Try this:
int a[]={156, 490, 647};
int b[]={218, 789, 461, 750};
int x=2, y=3;
float result;
result = (float) ( a[x] - b[y]) * 0.05 + 50;
printf ("%.2f", result);

C printf of a long type array not properly working [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.
My C has a behavior I do not understand.
I have defined an array as following
long gainT1[21];
I do some work with that variable (so, no need for an initialization), then, later, I would like to display the values that it contains. And here comes the problem: The first value showed by the second for is not the expected one!
printf("CHECKING: gainT1[0]=%ld\n", gainT1[0]);
{
ptrdiff_t k;
for(k = 0; k < 16; k++) printf("[%td]=%ld ", k, gainT1[k]); printf("\n");
for(k = 0; k < 17; k++) printf("[%td]=%ld ", k, gainT1[k]); printf("\n"); // Here the for is going up to 16 instead of 15 previously
}
this code returns:
CHECKING: gainT1[0]=4207440
[0]=4207440 [1]=4207440 [2]=4294967295 [3]=139846275105333 [4]=16351504 [5]=0 [6]=139846268659528 [7]=139846277253568 [8]=16351504 [9]=3 [10]=128 [11]=139846277252304 [12]=4294967295 [13]=139846272645590 [14]=0 [15]=0
[0]=2356216002 [1]=4207440 [2]=4294967295 [3]=139846275105333 [4]=16351504 [5]=0 [6]=139846268659528 [7]=139846277253568 [8]=16351504 [9]=3 [10]=128 [11]=139846277252304 [12]=4294967295 [13]=139846272645590 [14]=0 [15]=0 [16]=6312008
I can't figure out what is wrong with my code.
"I do some work with that variable" is rather undefined. If, in the for-loop, you're accessing an element that's actually still undefined, anything can happen, including odd values showing up.
So, easiest is simply to do:
long gainT1[21] = { 0 };
Any non-set value will then at least be zero.
(Note: I know this array initialization works for c99; not sure about eg c89 or c90.)
If you show the whole code then it will be easy to get the exact error but as you have provided less code so I think you should try this.
You can use printf() to display a ptrdiff_t. According to the 1999 C Standard, the format string should contain the t length modifier with the d or i conversion specifier, as in:
ptrdiff_t d;
...
printf("%td", d);
Although the %d specifier has been around as long as C, the %t modifier is fairly new. Few C libraries support it yet.
If your compiler doesn't support %td, then you should try %ld, as in:
printf("%ld", (long)d);
Displaying a ptrdiff_t using the Standard C++ iostream library is a simple as displaying any other numeric type:
std::cout << d;
As you helped me understanding that the problem must be somewhere else, I created a new project deleting as much lines as possible and it appears that it is an initialization problem: as the array is not initialized properly, the value is not stable. The problem appears or not depending of compiling options, so let's keep in mind to always initialize variables properly even when it seems useless.

decrement prefix as condition in c while loop [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.
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

Please explain why the output does not change whatever be the value of i [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.
#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.

Resources