开发者

Type during array Initialization

If in my program, I have this:

int arr[some_number];

What is the type of开发者_运维知识库 some_number?

  1. Integer?
  2. Unsigned integer?
  3. Automatically determined (long, unsigned long etc.)

This might be a hypothetical question (assuming I can allocate as much memory as needed at compile time), just curious to know if type of some_number is always integer.

**EDIT In case my language is not clear, on a system where sizeof(integer) is 2 bytes and I define array like:

int arr[65537] , will "65537" overflow and it is effectively, int arr[-1]?


some_number must either be an actual positive integer as in:-

int arr[1024]

or it can be a MACRO which resolves to a positive integer:-

#DEFINE some_number 1024
int arr[some_number]

As the interpretation is done at compile time and there are no program variable is used then there is no "type".


By default in C, the type of a number is int. You can use the suffix u to make it an unsigned integer, the suffix l to make it a long (and with some compiler the suffix ll to make it a long long, ie. a 64-bit integer).


Type of an expression doesn't depend on the context, so the type of some_number (some_expression actually) will be the same as if it was used not in the array definition. Another question is what types of expressions are allowed for designation of the array size.


I think it is of type size_t, which can differ from one platform to another. It's unsigned, that's for sure. Look at this.


some_number must be TRUE constant ,it cann't be variable. for example

 main()
{
int a=1;
int kk[a]={1};
}

It would result an error saying

 variable-sized object may not be initialized

However we can not also use

int const a;

as array subscript beacuse const is not consider as true constant in C.


Supposing this is a definition inside a function, some_number can be any integral expression with a strictly positive value. If it is non-constant, the beast is called variable length array, VLA.

If you place it in outer scope or make it static, it has to evaluate to something that is constant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜