operator has no effect

O

onkar

#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
~m;
printf("%x\n",m);
return 0;
}


gives me :
$ gcc -Wall -g -o test test.c
test.c: In function `main':
test.c:4: warning: statement with no effect
$ ./test
fdff


whereas this works out properly :

#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
printf("%x\n",~m);
return 0;
}

$gcc -Wall -g -o test test.c
$ ./test
ffff0200


Why ???
 
I

Ian Collins

onkar wrote:

Please don't top post.
I mean than why did the second case work ??
Because you were passing ~m to printf. ~m on its own doesn't change m,
it just evaluates the expression and discards the result.
 
Z

Zara

#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
~m;

You complement m and do nothing with result. As complementing an
unsigned int has no effects, then the operator has no effect.
printf("%x\n",m);
return 0;
}


gives me :
test.c:4: warning: statement with no effect
whereas this works out properly :

#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
printf("%x\n",~m);

You now complement m and use its result to pass it to printf, thus the
operator serves some clear purpose and does have effect.
return 0;
}
Regrads,

Zara
 
R

Richard Heathfield

onkar said:
#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
~m;

This is an expression, and C likes to evaluate expressions. In this case,
the expression ~m is evaluated, and you do nothing with the result. m is
not changed.
printf("%x\n",m);
return 0;
}


gives me :
$ gcc -Wall -g -o test test.c
test.c: In function `main':
test.c:4: warning: statement with no effect
Right.

$ ./test
fdff


whereas this works out properly :

#include<stdio.h>
int main(void){
unsigned int m=0xfdff;
printf("%x\n",~m);

Here, you use the ~m expression as an argument to printf, so its value /is/
used, so it does have an effect on the program.

But m's value is unchanged. Add this line to your program:

printf("And the value of m is still %x\n", m);

If you want to change m's value, you will want to use some kind of
assignment statement.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: normal service will be restored as soon as possible. Please do not
adjust your email clients.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top