How does the working of compiler differs in both cases although in both cases, n is unknown to compiler during compile time? [closed]

StackOverflow https://stackoverflow.com/questions/16242504

  •  13-04-2022
  •  | 
  •  

Question

Code 1:

int n;
int c[n];
scanf("%d",&n);

Code 2:

int n;
scanf("%d",&n);
int c[n];

The first one gives segmentation fault but second one works fine.

Was it helpful?

Solution

Since both code segments use an uninitialized variable, they invoke undefined behavior (Not to mention that you are passing in an int where you should be passing in an int*. With undefined behavior the compiler makes no guarantees about what will happen. It could crash as in the first case, produce no error in the second case, or make demons fly out your nose.

What's happening is that in once case n has a value that happens to be set to a writable address and in the other it doesn't.

OTHER TIPS

int n;     // n is uninitialized
int c[n];  // you're trying to declare an aray with an uninitialized value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top