if() bug?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi

I noted today strange behavior, lets say I got something like that:

uint8_t x;
x = 1;

if( x )
{
    //do something
}

The problem is do something is never executed!
I have to replace the above with:

if( x != 0 )

and it works. I do not believe it's a bug - it's too simple. What's wrong?

GCC version 20100110
optimization: -O2 an -O3
chip: atmega16

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Your examples are exactly the same (from C point of view). Please post the complete code.
Is x modified inside an ISR (in this case you need to declare x as volatile uint8_t x)?

/Martin.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

mogor wrote:
Hi

I noted today strange behavior, lets say I got something like that:

uint8_t x;
x = 1;

if( x )
{
    //do something
}

The problem is do something is never executed!

The compiler is probably optimizing your code your code away. You can tell by looking at the resulting assembly code that it generates.

Declare your x variable as either const, like so:
const uint8_t x = 1;

Or declare it as a 'volatile' and I bet the compiler will generate the correct code.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:

You can tell by looking at the resulting assembly code that it generates.

As Eric says always start by studying the .lss file to see the underlying Asm if you think something is not working right, it will almost certainly be immediately apparent what's actually happened.