Filip Grkinic Filip Grkinic - 3 months ago 14
C Question

Why does compiler gives me error unusued variable n?

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

int main (void)
{
printf("Welcome to blabla\n");


// This next part gets user input and checks if the integer given by user is between 1 and 8

int n;
do
{
printf("Give me a integer between 1 and 8.\n");
int n = GetInt();
}
while (n >= 1 && n <= 8);

printf("You picked the number %d.\n", n);

return(0);
}

Answer

This line:

int n = GetInt();

tries to declare a new local variable n. It's completely separate from the local variable you declared earlier:

int n;

When you call GetInt(), you just want to assign the value to the existing variable, like this:

n = GetInt();