can we declare a array as, int arre[x];
and assign the value of x as,x=5;
but error is coming "constant expression required."
Any help?

i wanted to input series of marks,first you should enter how many subjects(if 5 subs,x=5)
then you can enter 5 marks.

Recommended Answers

All 5 Replies

can we declare a array as, int arre[x];
and assign the value of x as,x=5;
but error is coming "constant expression required."
Any help?

i wanted to input series of marks,first you should enter how many subjects(if 5 subs,x=5)
then you can enter 5 marks.

Yes you can do it...

int main()
{
        int x;
        cin>>x;
        int a[x];
        for(int i = 0;i<x;i++)
        {
                cin>>a[i];
                cout<<"\n"<<a[i];
        }
        return 0;
}

no you can't my compiler produces this error

bytes.cpp:8: error: ISO C++ forbids variable-size array `a'

Variable size arrays are not part of C++ (they are a part of C99) if your compiler allows that code in C++ then it is using an extension to the standard.

In standard C++ you have to do it by allocating (new) the array once you know the size and deleting it afterwards.

#include <iostream>
using namespace std;

int main()
{
	int x;
	cin>>x;
	int* a = new int[x];
	for(int i = 0;i<x;i++)
	{
		cin>>a[i];
		cout<<"\n"<<a[i];
	}
	
	delete[] a;
	return 0;
}
commented: thanks +0

no you can't my compiler produces this error

bytes.cpp:8: error: ISO C++ forbids variable-size array `a'

Variable size arrays are not part of C++ (they are a part of C99) if your compiler allows that code in C++ then it is using an extension to the standard.

In standard C++ you have to do it by allocating (new) the array once you know the size and deleting it afterwards.

#include <iostream>
using namespace std;

int main()
{
	int x;
	cin>>x;
	int* a = new int[x];
	for(int i = 0;i<x;i++)
	{
		cin>>a[i];
		cout<<"\n"<<a[i];
	}
	
	delete[] a;
	return 0;
}

Thanks for you valuable suggestion ... but my compiler is not producing this error.

Like I said it is probably using an extension which compiler are you using?

@msgeek

Please read the thread carefully. He/She has explained why your compiler might not be complaining.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.