Code compiles, but sketch is too short

I have a sketch that should compile to about 18K, at least it did. Now it compiles to just under 7K, and won’t produce any results when uploaded.

Here’s the guilty code:

unsigned int
analogRead100 (byte reg)
{
  unsigned long analog = 0;
  for (byte ai = 0; ai < 128; ai++)
  {
    analog += analogRead (reg);
  }
  return (analog >> 7);
}

Now if I change the loop to

unsigned int
analogRead100 (byte reg)
{
  unsigned long analog = 0;
  for (byte ai = 0; ai < 256; ai++)
  {
    analog += analogRead (reg);
  }
  return (analog >> 8);
}

It will compile, not throw any errors, but generate a sketch that’s only 7K and won’t run… OK, the second loop will always fail as the byte will roll over before reaching 256, but still - shouldn’t the compiler throw a warning or something before optimizing away most of the code?
:astonished:

Here’s the guilty code:

That is what they all say. Posting what you think is the problem is very rarely where the problem is. That is why we ask for all the code.

but still - shouldn’t the compiler throw a warning or something before optimizing away most of the code?

It might do but by default warnings are suppressed.

but still - shouldn't the compiler throw a warning or something before optimizing away most of the code?

No, it shouldn't. You shouldn't write dumb code that will be optimized away.

  for (byte ai = 0; ai < 256; ai++)

Isn’t optimized away, but the compiler can spot that it’ll never finish, so optimize away anything after calls to
analogRead100(), which is a completely valid optimization/transformation of the code.

byte variables always contain a value less than 256. To loop 256 times with a byte variable you have to
use do … while as in:

  byte ai = 0 ;
  do
  {
    ....
  } while (++ai != 0) ;

MarkT: To loop 256 times with a byte variable you have to use do .. while

I'd much rather use a plain old for loop with an int variable, rather than use an awkward construct to force the byte variable to do the same job.