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?

Eric Postpischil
232k15 gold badges197 silver badges377 bronze badges
asked Nov 22, 2020 at 11:38
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.

answered Nov 22, 2020 at 11:49
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;
}
answered Nov 22, 2020 at 12:01

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.