I have completed greedy from pset1 and I still doubts about the variable declarations and the function position. What is the difference if they are declared inside or outside the main function?

#include <math.h>
#include <stdio.h>
#include <cs50.h>

// variable declaration
float change = 0;
int count = 0;

// function declaration
int change_function(x)
while (change >= x)
    change = change - x;
return 0;

int main(void)
    // keeps printing prompt if input < 0 
        printf("Hi monseur! How much change is owed?\n");
        change = GetFloat();
    while (change < 0);

    // float to int and rounds number
    change = (int) round(change *100);

    printf("%i\n", count);

The difference between where a variable is declared is scope. Strictly for this discussion, consider main to be a function, even though it is a special one.

A local variable is a variable declared inside of a function is local to that particular function. It exists only inside the function where it was declared and cannot be directly accessed by any other function. If another function creates a local variable with the same name, it will actually be a different variable entirely, and totally independent. When a variable needs to be shared between functions, they are passed by copy - a copy of the current value is sent to the new function as a parameter. Alternatively, the address of the original value may be sent to the new function to access the origianal variable.

A global variable is declared outside of main and outside of any function. It exists across the entire program, can be accessed directly, and is available to all. The down side of this is that it can cause problems. In team programming, different people will have to write different functions, which will have to work together later. They will be able to name variables within their own function without having to worry about what someone else is writing, since the vars will be local. BUT, when global vars are introduced, everyone will have to worry about what everyone else is doing. One mistake with global vars can corrupt an entire project.

Another problem occurs when there is a global variable and someone declares a local variable with the same name. This is called creating a shadow variable. The local shadow will take precedent in the local function, leaving the global unchanged. Once the function completes execution, the local shadow variable ceases to exist and the global reasserts itself.

Global variables should be used very sparingly. Some people say that they should never be used, but the truth is that they are, on occasion, the right tool to use. Before creating a global variable, you should have a really good reason for doing so.

There will be more discussion about scope as the course continues.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .