Home > front end >  Array dimension in C
Array dimension in C

Time:03-25

I know that arrays need to be defined with a size that cannot be modified, but in this code, the counter i exceeds the size of the array (because of the 2 in "i<sz 2" in the for loop) but the code don't give any errors, why? another question: is it correct to use std::cin to assign the value to sz or should I assign the value of sz when I declare the variable?

#include <iostream>

int main() {
    int sz;
    std::cin >> sz;
    int v[sz];
    std::cout << "i" << " " << "v[i]" << std::endl;
    for(int i=0;i<sz 2;i  ){
        std::cin >> v[i];
        std::cout << i << " " << v[i] << std::endl;
    }
    return 0;
}

CodePudding user response:

the counter i exceeds the size of the array (because of the 2 in "i<sz 2" in the for loop) but the code don't give any errors, why?

Going out of bound of the array(as you're doing) is undefined behavior.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


Additionally, in Standard C the size of an array must be a compile time constant. So when you wrote:

int sz;
std::cin >> sz;
int v[sz]; //NOT STANDARD C  

The statement int v[sz]; is not standard C because sz is not a constant expression.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

  • Related