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.

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;
}

Edited 6 Years Ago by WaltP: Added CODE Tags

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;
}

Edited 6 Years Ago by Banfa: n/a

Comments
thanks

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.

@msgeek

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

Edited 6 Years Ago by thomas_naveen: to avoid confusion

This article has been dead for over six months. Start a new discussion instead.