0

What am i doing wrong in this code ? There are no errors but if i enter a 4 digit number the output it is 1272 !!

#include<conio.h>
#include<stdio.h>
void main()
{
    int i,n=0;
    clrscr();
    printf("Enter a number");
    scanf("%d",&i);
    while(i>=9)
    {
        i=i/10;
        n++;
    }
    n++;
    printf("This is a %d digit number",n);
    getch();
}

2 Answers2

2

It's undefined behavior because you have used uninitialized local variable.

Do not use automatic storage variable before it has been initialized yields undefined behavior

C standard is 6.3.2.1 p2:

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

Just initialize your variables and avoid a potential headache in the future.

So, in your program initialize n to 0.

int n = 0;
msc
  • 33,420
  • 29
  • 119
  • 214
1

Initialize n to 0. You are incrementing whatever garbage value is in memory for n.

msc
  • 33,420
  • 29
  • 119
  • 214
starlight
  • 130
  • 1
  • 18