c - int i in a for loop vs not -
why following not work when defined in loop
#include <stdio.h> #include <math.h> int n; long long int h() { long long int ans=0; int i, lt; if(n <= 0) return 0; for(i=1, lt=sqrt(n); i<=lt; i+=1) /* if i=1 replaced int i=1 => garbage */ ans+=(n/i); ans = 2*ans-(lt*lt); return ans; } int main() { scanf("%d",&n); printf("%lld\n",h()); return 0; }
output when it's defined @ top
input: 8 output: 20
output when it's defined in loop /* (int i=1 ..) */
input: 8 output: 1243068212
i see warning lt initialized when used here
, why?
when write this:
int lt; (int i=1, lt=sqrt(n); ...)
that defines two new inner variables named i
, lt
; in particular, new lt
variable shadows outer one, making temporarily inaccessible within inner scope. so, outer lt
variable never gets initialized, , when compute ans = 2*ans-(lt*lt)
, it's using uninitialized value compute result.
Comments
Post a Comment