Operation undefined

  • Thread starter Christian Christmann
  • Start date
C

Christian Christmann

Hi,

for this code

int main( void )
{
unsigned short a= 10;
a = (a <<= 1) ^ 4129; //warning concerns this line
return 0;
}

gcc issues the warning:

warning: operation on `a' may be undefined


The problem is "(a <<=1 )" before the XOR operator, but
why might this expression lead to undefined behavior?

Regards,
Chris
 
R

Robert Gamble

Christian said:
Hi,

for this code

int main( void )
{
unsigned short a= 10;
a = (a <<= 1) ^ 4129; //warning concerns this line
return 0;
}

gcc issues the warning:

warning: operation on `a' may be undefined


The problem is "(a <<=1 )" before the XOR operator, but
why might this expression lead to undefined behavior?

The operation is undefined because a is modified twice without an
intervening sequence point. Why not just use "a = (a << 1) ^ 4129" ?

Robert Gamble
 
M

Martin Ambuhl

Christian said:
Hi,

for this code

int main( void )
{
unsigned short a= 10;
a = (a <<= 1) ^ 4129; //warning concerns this line
return 0;
}

#include <stdio.h>

int main(void)
{
unsigned short a = 10;
#if 0
/* the following is a variation on 'i = i++;' covered by the FAQ */
a = (a <<= 1) ^ 4129;
#endif
/* but this should work */
a = (a << 1) ^ 4129;
printf("a was 10, and is now %u\n", a);
/* and this should work */
a = 10;
a = (a << 1);
a ^= 4129;
printf("a was 10, and is now %u\n", a);
return 0;
}
 
A

Andrew Poelstra

Hi,

for this code

int main( void )
{
unsigned short a= 10;
a = (a <<= 1) ^ 4129; //warning concerns this line
return 0;
}

gcc issues the warning:

warning: operation on `a' may be undefined


The problem is "(a <<=1 )" before the XOR operator, but
why might this expression lead to undefined behavior?

I'm pretty sure this is a (potential?) sequence-point error, and
that is what gcc is warning you about. It appears to me that using
(a <<= 1) is logically equivilant to (a << 1) in this context:

int main (void)
{
unsigned short a = 10;
a = (a << 1) ^ 4129;
return 0;
}
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top