0

Can you please help me why int i becomes -4912 (see the picture) when it should start from 1? Thank you very much.

int main(void)
{
    long long n = 4003600000000014;
    int i;
    int num;
    for (i = 1; i < 15; i += 2)
    {
        int digit = (n / pow(10, i));
        printf("%i\n", digit);
    }
}

enter image description here

7
  • 2
    When do you check the value of i? Before it's assigned to by the for loop? What happens if you step once in the debugger? Commented Apr 14, 2021 at 7:28
  • 2
    Is an int on your system large enough to hold the values returned by that equation? Commented Apr 14, 2021 at 7:31
  • 1
    Seems that i isn't initialized yet. Make sure the break point is at line 19 Commented Apr 14, 2021 at 7:31
  • 1
    The first chapters of any C programming book typically addresses numerical limits of integers. Do you think that 4003600000000014 / 10^1 will fit inside an int? Commented Apr 14, 2021 at 7:32
  • 1
    line 3 doesnt initilize i so it gets a random stack value until it is set to 1 in the for-loop. Commented Apr 14, 2021 at 7:33

3 Answers 3

3

In your picture, the debugger is at the for loop. At that point the for loop initialization has not happened yet and i will have an arbitrary value.

Tell the debugger to "step". The initialization of the for loop will then be executed and you will see thati is now 1.

Sign up to request clarification or add additional context in comments.

Comments

-1

you should use %d in your printf and not %i I think.

Just try to initialise i : int i = 0; for example

or declare i in your loop : for(int i = 1; i < n; i++)

2 Comments

They're equivalent. %d is more common, but %i works fine.
yeah, with some researches i saw it. thanks
-1

Here you can read more about uninitialized variables. But as a short summary. A variable gets whatever random value is in the memory location until it is set. C/C++ does not initialize variables to 0 by default, it is the responsibility of the programmer. Uninitialized variables are sources to many bugs and are usually pointed out by compilers if the warnings are configured to be on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.