Could you please help me find out about variable scope? Below is a program for the CS50 Scrabble assignment.
I initialized score1 = 0, score2 = 0
atop. I thought since they are global variables, when they are manipulated in one funciton (compute_score
), its effect carries through to every other function without my overwriting them. But, it seems that the values of both varialbes are unchanged throughout the program, and as a result I get "Tie!" in the end everytime I run the program. Could you explain why this happens for me? Thank you so much in advance!
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
int score1 = 0, score2 = 0;
int compute_score(string word, int score);
int main(void)
{
// Prompt the user for two words
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Compute the score of each word
compute_score(word1, score1);
compute_score(word2, score2);
// Print the winner
if (score1 > score2)
{
printf("Player 1 wins!\n");
}
else if (score1 < score2)
{
printf("Player 2 wins!\n");
}
else
{
printf("Tie!\n");
}
}
int compute_score(string word, int score)
{
// Compute score for each character
for (int i = 0, len = strlen(word); i < len; i++)
{
if (isupper(word[i]))
{
score += POINTS[word[i] - 'A'];
}
else if (islower(word[i]))
{
score += POINTS[word[i] - 'a'];
}
}
return score;
}