0

I keep getting this error: 'declaration shadows a variable in the global scope'

how do I fix it ?

here is my code

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

// set up

int count_sentences(string word);
int count_words(string word);
int count_letters(string word);

int letter;
int word;
int sentence;

int main(void)
{
    // Get input from reader
    string sample = get_string("text sample: ");

    int i = strlen(sample);

    // grade math

    float L = 100 * (letter / word);
    float S = 100 * (sentence / word);
    int index = 0.0588 * L - 0.296 * S - 15.8;

    //print grade
    {
    if (index < 1)
    {
        printf("Before Grade 1");
    }
    else if (index > 16)
    {
        printf("Grade 16+");
    }
    else
    {
        printf("Grade %i\n", index);
    }
    }
}

    // Score input

int count_letters(string sample)
{
    int letter = 0;
    for (int i = 0, n = strlen(sample); i < n; i++)
        if (isalpha(txt[i]))
        {
            letter++;
        }
    return letter;
}

int count_sentences(string sample)
{
    int sentence = 0;
    for (int i = 0, n = strlen(sample); i < n; i++)
        if (isalpha(txt[i]))
        {
            sentence++;
        }
    return sentence;
}

int count_words(string sample)
{
    int word = 0;
    for (int i = 0, n = strlen(sample); i < n; i++)
        if (isalpha(txt[i]))
        {
            word++;
        }
    return word;
}

1 Answer 1

1

"Shadowing" is the creation of a local variable with the same name as a global variable. This is an extremely dangerous practice and ties into the reason for not using global variables unless absolutely, absolutely necessary.

This code has declared all 3 globals, letter, word and sentence, inside of a function. That's why you're getting the warnings. There are ways to fix this using globals, but you'd be better served to figure out how to rewrite the code without globals. Globals are an invitation to insert logic errors and bugs into software and are to be avoided unless absolutely necessary. (There are always exceptions, but are a bad practice.)

That explains the warnings. Since none of the functions are called anywhere, there remains code to be written. If you have any issues after reworking the code, please post a new question.

You must log in to answer this question.

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