Array index related question

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Post Reply
Message
Author
User avatar
mahaju
Posts: 487
Joined: Mon 11 Oct 2010, 07:11
Location: between the keyboard and the chair

Array index related question

#1 Post by mahaju »

Hi
is this code legal?

Code: Select all

.
.
.
    uint e;
    int i, j;
    e = (unsigned int) ceil( (NO_OF_BITS + 1)/NO_OF_BITS_IN_WORD ) ;

    uint M[e*NO_OF_BITS_IN_WORD],
		Y[e*NO_OF_BITS_IN_WORD], temp_Y_to_store_group[NO_OF_BITS_IN_WORD],
		S[e*NO_OF_BITS_IN_WORD], X[NO_OF_BITS], C[2]={0,0};
.
.
.
let me explain why I am asking this

I am sure something like this used to be illegal when I was beginning to study C++

Code: Select all

int main(){
    int i,j;
    cout<<"Number of elements: "; cin>>i;
    int arr[i];
    for(j=0;j<i;j++){
        cout<<"element no "<<j<<" >> "; cin>>arr[j];
    }
    for(j=0;j<i;j++)
        cout<<"You entered"<<endl<<"a["<<j<<"] = "<<arr[j]<<endl;
    return 0;
}
We used Turbo C++, and the reason for it being illegal is that array index should be a constant positive integer and in this code the variable i get's it's after only at runtime. One of the reasons why we had to study calloc/malloc and new/delete. But now when I run it in gcc it seems to be completely legal and compiles easily. What is up with that? Have I already become that old? I would guess it is due to some sort of features added into the compiler but I don't know for sure?

However, this is my main question. In my first code, NO_OF_BITS and NO_OF_BITS_IN_WORD are constants defined using #define. So during each run of the program the value of e should be fixed. However, the variable e gets it's value from a function. Does this make it same as getting it from a cin? I need to use e to define array size later on, so is this legal? gcc seems to compile it anyway so I just need to make sure.

by the way, uint is typedef unsigned int

Post Reply