-3

I created an array of size N, where N is a variable and not initialized. arr[N] is of variable size. It should give an error but it runs fine.

#include<iostream>
    using namespace std;
    int time_calculator(int ,int *,int );
    int main(){
    int N,RN,i;
    int arr[N];
    cin>>N;
    cin>>RN;
    for(i=0; i<N ; i++)
        cin>>arr[i];
    int time=time_calculator(N,arr,RN);
    cout<<"time required= "<<time<<" sec";
    return 0;
    }        
       
int time_calculator(int n, int * s, int rn){
    int sm=*s;    
    for(int i=0;i<n;i++) 
    if(sm>*(s+i)){
      int t=sm;
      sm=*(s+i);
      *(s+i)=t;
      }
    return rn-sm;
}

Here I created an array of variable size, but the code runs fine. The array is not created dynamically. sm is a variable for the smallest element of arr, initialized by arr[0]. s is a pointer to arr. Please tell me why an error is not thrown.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • 1
    Probably a non-standard language extension combined with undefined behavior; don't rely on this. Instead use `std::vector arr(N);` ***after*** you've read `N` from `cin` – fabian Jun 19 '21 at 06:18
  • 1
    I checked this code in visual studio code and codeblocks. both ides doesn't gave any error. –  Jun 19 '21 at 06:21
  • 1
    Right, no syntax *error*, but if that is all you checked, you should read [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756) as there is a *warning* when compiling your code. – JaMiT Jun 19 '21 at 06:33
  • 1
    @CODEr *I checked this code in visual studio code and codeblocks* -- You should be checking the *compiler* being used under the hood, not the IDE. Visual C++ that comes with Visual Studio will refuse to compile the code. Those IDE's you're using are probably using `g++`, which allows this non-standard syntax. – PaulMcKenzie Jun 19 '21 at 07:33

2 Answers2

0

N is uninitialized when creating arr. You don't know how big of an array arr is. It might be 0, in which case you are overwriting your array. Or it might be some large number and you have plenty of space to store your integers.

Either way, this is undefined behavior. I suggest looking at std::vector as a replacement.

Jonathan
  • 694
  • 1
  • 6
  • 13
0

The problem is not it being uninitialized, but rather not being a compile-time constant.

The program is ill-formed (i.e. not valid C++) because of this.

Most compilers don't enforce strict standard compliance by default, but you can configure them to do it. For MinGW/GCC you could use following flags: -std=c++xx -pedantic-errors -Wall -Wextra, where xx is the language version (one of: 98, 11, 14, 17, 20). The last two flags are not strictly related to compliance (they merely enable the warnings), but it's a good idea to use them.

With those flags the code no longer compiles. I get error: ISO C++ forbids variable length array 'arr'.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207