0

Having this C code:

#include <stdlib.h>
#include <stdio.h>

long int sum(int n){
   int m[n]; 
   double sum = 0.0;  
   for(int i = 0; i < n; m[i] = rand(), sum += m[i], i++); 
   return sum; 
}

int main(int argc, char ** argv){
    printf("Rand sum: %ld", sum(8)); 
}

When I execute trying different arguments for the sum function, it always returns the same value even tough I'm am generating random numbers. If I print the generated numbers on each iteration, it indeed generates different values, but the sum is always getting the same result. These are some results given the argument value: n=8 -> sum=127071,n=6 -> sum=86235, n=10 -> sum=178497

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 8
    You forgot to seed you RNG. – Eugene Sh. Jan 12 '22 at 15:47
  • Unrelated: What's the purpose of the `int` array `m`? – Ted Lyngmo Jan 12 '22 at 15:47
  • @TedLyngmo I'm learning variable-size stack frames inspecting the generated assembly code and decided to write this function and assemble it. Then I found that behaviour. – Rafale garcia Jan 12 '22 at 15:49
  • Did you read the manual page for `rand`? – lurker Jan 12 '22 at 15:49
  • @lurker No. I shoud've done that first. )= Sorry. – Rafale garcia Jan 12 '22 at 15:51
  • 1
    @Rafalegarcia Is the VLA even seen in the assembly if you turn on max optimization? It could i theory be replaced with `long sum(int n) { double sum; for(int i = 0; i < n; ++i) sum += rand(); return sum; }` Btw, why are you mixing types? – Ted Lyngmo Jan 12 '22 at 15:55
  • "_If I print the generated numbers on each iteration, it indeed generates different values, but the sum is always getting the same result._" Would you mind to provide these examples? I don't understand how you have different values but the same sum. – the busybee Jan 12 '22 at 16:00

0 Answers0