1

I know the following is valid code:

#define SOMEMACRO 10
int arr[SOMEMACRO];

which would result as int arr[10].

If I wanted to make an array 2x size of that (and still need the original macro elsewhere), is this valid code?

#define SOMEMACRO 10
int arr[2 * SOMEMACRO];

which would be int arr[2 * 10] after precompilation. Is this still considered as constant expression by the compiler?

After a quick look it seems to work, but is this defined behavior?

1
  • 1
    Yes, that's evaluated at compile time and used as a constant. Commented Jul 30, 2013 at 10:28

4 Answers 4

2

Yes it will work.MACRO will be placed as it is at compilation so a[2*SOMEMACRO] will become a[2*10] which is perfectly valid.

To check what is preprocessed you can use cc -E foo.c option

Sign up to request clarification or add additional context in comments.

Comments

1

Is this still considered as constant expression by the compiler?

Yes. That's the difference between a constant expression and a literal: a constant expression need not be a single literal, bit it can be any expression of which the value can be computed at compile time (i. e. a combination of literals or other constant expressions).

(Just for the sake of clarity: of course literals are still considered constant expressions.)

However, in C, the size of the array need not be a compile-time constant. C99 and C11 supports variable-length arrays (VLAs), so

size_t sz = // some size calculated at runtime;
int arr[sz];

is valid C as well.

Comments

1

Yes you can use this expression. It will not result in UB.
Note that an array subcript may be an integer expression:

#define i  5 
#define j  4
int a[i+j*10] = 0;

The value of of subscript i+j*10 will be calculated during compilation.

Comments

0

yes, as long as it a valid number it's a constant expression. and if you say it worked then you know the compiler worked just fine with it.

as you know we can't do

int x;
scanf("%d", &x);
int arr[2 * x];

because that's no a constant number. but what you've written is a constant number, so you're good to go

3 Comments

i think second we can do with new compilers
"we can't do" - we can, do you happen to live before 1999?
This is valid in C99.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.