In the numberOfDigits
function, I didn't assign a value to the digits
variable because by default it's 0. But then in the printf
statement for digits
variable it got printed as 168.
I got the expected output after I assign zero to the digits
variable. So, my question: is it necessary to assign values for the variables in a user define function? If yes why?
#include <stdio.h>
void numberOfDigits(int num);
void main()
{
int num;
printf("Enter integer :");
scanf("%d",&num);
numberOfDigits(num);
}
void numberOfDigits(int num)
{
int nc=num, digits=0;
while(nc>0)
{
nc=nc/10;
digits ;
}
printf("Number of digits in %d are %d\n",num,digits);
}
CodePudding user response:
From the C Standard (6.7.9 Initialization)
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
Within the function numberOfDigits
the variable digits
has automatic storage duration because it is declared (in a block scope) without a storage class specifier. So if it is not initialized explicitly then its value is indeterminate. And applying the increment operator results in undefined behavior.
If you will declare the variable for example like
static int digits;
then it will be zero-initialized (only once).
Pay attention to that the function has a bug. If the user will pass to the function zero ( 0 ) then the function will report that the number has 0 digits though it has one digit equal to 0.
You need to substitute the while loop for the do while loop shown below
do
{
digits ;
} while ( nc /= 10 );
CodePudding user response:
I am assuming you are quite new to C.
Maybe it does help to review at what place in memory different types of variables are stored. Local variables, variables created in functions (such as in your case), are always allocated memory in the program stack. However, there is no real guide-line that promises your program that the stack is zero'ed out. This means, when you are creating a local variable, it gets assigned memory in the stack and that memory space can be a non-zero value. Then when you print that integer (without assigning it) you will see what was stored before at the same memory address.
Hence, there is no guarantee that a value is 0 when you do not define it.
You can learn more here.
CodePudding user response:
...because by default it's 0
False, for local (automatic-duration) variables.
So, my question: is it necessary to assign values for the variables in a user define function?
Yes.
If yes why?
Because otherwise they start out with unpredictable values, making your code unreliable and broken.
See also this answer.