Const Array Topic is solved

If you have a simple question and just want an answer.
cschopges
Member++
Posts: 28
Joined: Mon Jul 25, 2016 2:03 pm

Const Array

Post by cschopges »

Hello everyone,

this must be a silly question, but I don't understand it, so please enlighten me:
I'm trying to define an array of constant size as arrays need to have constant size in XC (or at least sizes known at compile time):

This just works fine:

Code: Select all

int main(){
    uint8_t received[4];

    return 0;
}
But when I want to do this, it doesn't work anymore:

Code: Select all

static const int N = 4;

int main(){
    uint8_t received[N];

    return 0;
}
I don't really understand what's wrong since N is const and static?
View Solution
robertxmos
XCore Addict
Posts: 169
Joined: Fri Oct 23, 2015 10:23 am

Post by robertxmos »

Hi cschopges,

'N' is a variable which occupies global memory and is initialised at runtime with the value 4.
The compiler will respect the 'const' placed on this variable as far as it is allowed and error if you break the rules. However, you could cast (or reinterpret cast in XC) the constness away and change the value - after all it is just a value in memory.

Variables can't be used for array sizing - even if they are const and the value known at the time the array is declared. Seems mean, but that is the way it is.

It seems odd in XC that you can have a 'static const int param' as a function argument and that can be used for sizing arrays.
But this is not C and in XC these are not variables, but 100% link time constants. Think of them as #defines for the linker rather than the preprocessor - quite useful and powerful!

Hope that helps.
User avatar
ers35
Active Member
Posts: 62
Joined: Mon Jun 10, 2013 2:14 pm

Post by ers35 »

Use an enum:

Code: Select all

// xcc -c -target=XCORE-200-EXPLORER array.xc

#include <stdint.h>

enum { N = 4 };

int main()
{
  uint8_t received[N];
  return 0;
}
cschopges
Member++
Posts: 28
Joined: Mon Jul 25, 2016 2:03 pm

Post by cschopges »

Hi,

Thank you both for your reply :)

I'm not sure how I could cast the constness away? but I think I understand your point:
I'm not defining an array of constant size, but an array of a size defined by a variable which I set to const.

Nevertheless you gave me the idea to write it like this:
#define N 4
which works perfectly fine. The enum works too :)

Thanks a lot, it actually helped
robertxmos
XCore Addict
Posts: 169
Joined: Fri Oct 23, 2015 10:23 am

Post by robertxmos »

// test.xc
static const int i = 0;
int main() {
unsafe {
int *p = (int*)&i;
*p = 1; // Change the value of i, even tho' it is declared const.
}
return i;
}

$ xcc test.xc -target=STARTKIT -O0
$ xsim a.xe
$ echo $?
1
cschopges
Member++
Posts: 28
Joined: Mon Jul 25, 2016 2:03 pm

Post by cschopges »

thanks