#include <iostream>
#include <string>
using namespace std;
int count_number_place(int number)
{
int number_placement;
while (number >= 1)
{
number_placement++;
cout << number_placement <<endl;
number/=10;
}
return number_placement;
}
int main(int argc, const char * argv[])
{
// insert code here...
int user_input_number;
cout << "Please enter your number here" << endl;
cin >> user_input_number;
cout << "User input number is "<< user_input_number <<endl;
cout << "The numbers of digits in the input number is :" << count_number_place(user_input_number) << endl;
return 0;
}
I'm trying to create a small program that calculates the number of digits of a given number.
Whenever I type in numbers like 200
the expected results is 3
. Instead I got 7963
. When I put a breakpoint at the line number_placement
I got a default value of 7961
which is weird because that value wasn't assigned anywhere in the code.
Can you please explain why I get that result?
If a variable has never been assigned a value, it holds the default value for its data type. For a reference data type, that default value is Nothing. Reading a reference variable that has a value of Nothing can cause a NullReferenceException in some circumstances.
Solution. If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value. Whenever we declare a variable, a location is allocated to that variable.
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.
To assign a value to a C and C++ variable, you use an assignment expression. Assignment expressions assign a value to the left operand. The left operand must be a modifiable lvalue. An lvalue is an expression representing a data object that can be examined and altered.
Just change your function to
int count_number_place(int number)
{
int number_placement = 0; // assign 0
while (number >= 1)
{
number_placement++;
cout << number_placement <<endl;
number/=10;
}
return number_placement;
}
That is, change
int number_placement;
to
int number_placement = 0;
If you try to access uninitialized variables, you will get garbage values because it is undefined behavior. The compiler will just give it some garbage values.
This link might be useful
What happens to a declared, uninitialized variable in C? Does it have a value?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With