Click here to Skip to main content
15,568,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. Im learning to code functions in C and was testing tis specifically:
When you use int test; in a function called example() that modifies the value of test and then in your main code you repeat the function example(). The value of test changes or keeps the same value.

So i was testing and wrote this code but the result is 4196044 which i dont understand why is that. My code was just suposed to add three to score by addding test. So in the first loop test is 3. So then i wanted to see if in the second loop test would be still 3 or it would be 6 meaning the variable test keeps its 3 value from the earlier loop and then adds another 3. Hope im making sense. thanks for reading.
The code is this ([C] test2.c - Pastebin.com[^])

What I have tried:

C++
#include <cs50.h>
#include <stdio.h>
int addthree(int var);

int main(void)
{
    int result;
    int score = 9;
    for (int i = 0; i < 2;i++)
    {
    result = addthree(score);
    }
    printf("%i\n", result);
}

int addthree(int var)
{
    int test;
    for (int i=0; i < 3; i++)
    {
        test = test + i;
    }
    var = var + test;
    return var;
}
Posted
Updated 16-May-20 3:00am
v3

Your int test; is uninitialized
 
Share this answer
 
v2
Simple: What is the value of the variable test?
Answer: Whatever was in stack memory at the time of declaration.
int test; // value undefined.
for (int i=0; i < 3; i++)
{
    test = test + i; // value undefined - unknown
}


Local variables do not default to 0 in the C or C++ languages. They contain whatever was already in the location at the time of declaration. You have to initialize them to a know value before you use them, or you cannot predict the answer before hand.

Do you get the same answer every time you run the program?
If you do, then, if you have the time, try to find out why. Knowing this will improve your understanding and allow you to recognise bugs before they happen and fix them when you find them in the future.
 
Share this answer
 
v2
Next time, use the debugger. You can inspect the content of variables from the first line of code. This was EASILY solvable with the debugger. It would have saved you a ton of time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900