c - How to solve uninitialized local variable used? -
this question has answer here:
- uninitialized local variable 'j' used 3 answers
#include <stdio.h> int main() { int x; int counter; while (scanf_s("%d", &x) != 0) { puts("enter signed number : "); if (x % 2 == 0) { counter=counter++; } } printf(" %d pair numbers", counter); }
i get
uninitialized local variable counter used.
the program supposed keep asking numbers until gets 0 , tells amount of pairs given.
the problem facing cause use of variable counter
without initializing it. compiler telling you.
when try execute counter=counter++;
first time, counter
has no definied value. might think int counter;
gets initialized 0
, wrong in c.
the next problem line counter=counter++;
itself. if want increment counter
, use counter++
. depending on compile using, use of counter=counter++
should give @ least warning. on machine using apple llvm version 8.1.0 (clang-802.0.42) get
warning: multiple unsequenced modifications 'counter' [-wunsequenced]
then try loop until read 0
. scanf()
(use instead of microsoft specific scanf_s()
) not return has read stdin
number of input items assigned. returns 0
in event of matching failure.
so here do:
- initialize
counter
- replace
counter=counter++
counter++
- use loop breaking condition return value of
scanf()
one approach following:
#include <stdio.h> int main() { int x=0; int counter=0; do{ printf("enter signed number: "); scanf("%d", &x); if (!(x % 2)){ counter++; } } while(x); printf(" %d pair numbers\n", counter); }
Comments
Post a Comment