0

Is this allowed in C Language as given below:

int a=2, b=3;
int arr[a+b];

Is this a valid C statement?

9
  • This isn't a declaration, just a normal array subscript expression. Commented Nov 22, 2020 at 11:40
  • 1
    Do you mean int a=2,b=3; int arr[a+b];? Commented Nov 22, 2020 at 11:41
  • It's only valid if arr is a pointer or array object declared.. somewhere. And even then, it's pointless as it doesn't actually do anything. Commented Nov 22, 2020 at 11:41
  • @Aman Sharma, you cant declare an array with local variable! The max you can do is create constats and do something like this: #define A = 2 #define B = 3 int arr[A+B]; Commented Nov 22, 2020 at 11:45
  • 2
    @LSerni: Testing like that shows only what one specific compiler does in one specific circumstance. It does not definitively reveal what the C standard says. Such a test could pass because a compiler supports an extension not defined by the C standard, and an assignment and print could appear to work even if their behavior were undefined by the C standard. So recommending such testing is not a good way to answer questions like this. Commented Nov 22, 2020 at 12:32

2 Answers 2

3

An array declare with a size that is not a integer constant expression is called a variable length array. It is allowed in C, although not for arrays with static or thread storage duration.

The 1999 C standard required C implementations to support variable length arrays. The 2011 standard made support optional.

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

Comments

1

You can do something like this:

#include <stdio.h>

#define A 2
#define B 3

int main(){
   
  int a=A, b=B, arra[A+B];

  return 0;
}

1 Comment

@4386427 No but, thats the best option! I will edit it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.