Reputation: 343
following code we always use and is alright,
while(int c=getchar() != 'q');
but if change the ints to pointers like below, compile will rise an error.
#include <stdio.h>
int main(){
int* c=0;
if(int* a =c !=0)
printf("ok");
}
error: cannot convert `bool' to `int*' in assignment
what had happened here? seems the priority was changed. can anyone give me a hint. and if I change it to this, it will work.
#include <stdio.h>
int main(){
int* c=0;
int* a;
if((a =c) !=0)
printf("ok");
}
Upvotes: 1
Views: 183
Reputation: 500753
No, operator precedence hasn't changed between the two code snippets. The following:
while(int c=getchar() != 'q')
is equivalent to:
while(int c = (getchar() != 'q'))
Here, getchar()
is called, its return value is compared to 'q'
, and the result of the comparison is stored in the int
variable c
.
In other words, c
doesn't contain the character that's just been read; it contains a boolean indicator saying whether the most recent character was 'q'
.
Since c
is never looked at, the code works. However, it is probably not what was intended.
Upvotes: 4
Reputation: 88438
You are indeed seeing precedence in action.
!=
has higher precedence than =
. So
int* a =c !=0
parses as
int* a = (c !=0)
which is an assignment of a bool
to an int*
Upvotes: 3
Reputation: 182684
Because of precedence, while(int c=getchar() != 'q');
is wrong. It will always store the result of comparing the value returned by getchar()
and q
. So c
will always be 1
or 0
.
You likely want:
int c;
while((c = getchar()) != 'q');
^ ^
Or maybe
while((c = getchar()) != EOF && c != 'q');
Upvotes: 6