Week 12

Just an aside before I write this week's blog, I have been keeping up with the lectures throughout the semester, I just haven't had a chance to do any of the blogs up till now due to the workload in my other modules.


Lab

This week's lab was a short but challenging one. There was a twist in it though that kept me on my toes, and that was how do I pass a variable to a function without modifying the function call, thus modifying the main function too much. That is when the solution hit me, make it a global variable. This much against my better judgement (and good coding practice that has been instilled in me from CE4703), was the only way to do this. To explain why this isn't good practice I'll first have to explain what is a global variable.

Global Variables

Global variables are variables that can be accessed by any function called by your program. Take these examples:

Sample 1

#include <stdio.h>
#include <stdlib.h>

int i = 0;

int main(){
    while(i < 10){
        printf("i equals %i", i);
        i++;
    }
    EXIT_SUCCESS;
}

Output:

 Expected value of i   Output 
0
i equals 0
1
i equals 1
2
i equals 2
3
i equals 3
4
i equals 4
5
i equals 5
6
i equals 6
7
i equals 7
8
i equals 8
9
i equals 9

Sample 2

#include <stdio.h>
#include <stdlib.h>

int sumbyten(int j);

int i = 0;

int main(){
    int sum = i;
    while(i < 10){
        sum = sumbyten(sum);
        printf("i equals %i", i);
        i++;
    }
}

int sumbyten(int j){
    int temp = j;
    i *= 10;
    printf("%i + %i = %i", i, temp, j);
    j += i;
    return j;
}

Output:

Expected value of i Actual value of i Expected Value of sum Actual value of Sum Expected Output Actual Output
0
0
0
0
0 + 0 = 0
i equals 0
0 + 0 = 0
i equals 0
1
1
0
0
10 + 0 = 10
i equals 1
10 + 0 = 10
i equals 1
2
10
10
10
20 + 10 = 30
i equals 2
N/A
3
30
30 + 30 = 60
i equals 3
4
60
40 + 60 = 100
i equals 4
5
100
50 + 100 = 150
i equals 5
6
150
60 + 150 = 210
i equals 6
7
210
70 + 210 = 280
i equals 7
8
280
80 + 280 = 360
i equals 8
9
360
90 + 360 = 450
i equals 9
10
450
N/A

As you can see from the above examples, global variables can be dangerous as they can be changed by any function in the program. In the program in Sample 1, the program works as intended but as you can see, in sample 2 the loop terminates after going through it once because i is changed by the sumbyten function, dispite the fact that the way that the program is written which is to go through it 10 times using the numbers 0 through to 9.This is because the function alters the value stored in i while it is running. It is because the functions can see this value is why it seems tempting but it's because of this fact that it isn't such a good thing at the same time as those functions can change the value, messing up the expected running of the program.