An alternative walk around this error

Why is it that this:

#define foo 100
int void something(uint16 x) // <--- foo is passed to x
{
    // do some stuff
    _delay_ms(x);
    // do some stuff
}

generates this error:

error: __builtin_avr_delay_cycles expects a compile time integer constant
  __builtin_avr_delay_cycles(__ticks_dc);

I understand the error but isn't the value in foo a constant value ??
or it's because foo is a storage in memory holding or pointing to the value
I strong believe that this is specific only to the programming of the mcu
but I want to use function something(uint16 x) for multiple reasons
depending on certain conditions.
Of course, I've tried

const int foo = 100;

I think there's a difference approach to this.
Thanks,

Not when you pass it to a function where the parameter is uint16.

The function has no idea you used a constant as the matching argument.

added: TBC, inside the function, x is a uint16. Nothing you do outside the function can change that.

It's part of the hole point about functions. They can't know anything beyond what they are told.

a7

1 Like

The value of 'foo' here is not a value stored in memory. This is a directive to the compiler to replace any instance of 'foo' in the program with the literal value 100 before compiling the instruction. Admittedly each instance of 'foo' will be consistently replaced so could perhaps be described as being constant, but it does not constitute a constant from the compilers perspective.

On the other hand:

does store the value in memory and references it each time 'foo' is used.

1 Like

Thus I'd have no choice to use multiple functions
and give _delay_ms() a constant values ?? example: _delay_ms(100);
There's no other alternatives ?

Thanks

The compiler has to know the value used for _delay_ms() at compile time. You could directly use foo in _delay_ms(foo), but you cannot use a value passed into a function because the compiler is not smart enough to determine that the only value ever passed into that function will be a single constant that is know at compile time.

< edit >
Apparently the compiler will inline the function and it will work properly, if you leave out the "other stuff" that you have removed from the function. Once you add in enough code that the compiler does not inline the function for optimization purposes, it will produce the error message.

1 Like

If you have a certain number of constants, you could write one function that took an index and use it in a switch statement where each case called delayms() with a constant.

Or you could write a macro, I'm not too good at it but

# define kDelay(x)  _delay_ms(x)

should be close and I will rely on the idea that posting something wrong is the quickest way to get corrected. :expressionless:

and use it like you want, x would, obvsly I hope, need to be a constant.

a7