Search code examples
cstructerror-handlingcompiler-errorsstructure

Variable undeclared even if it was in C program


There is an error that says that book is undeclared and a note that says "each undeclared identifier is reported only once for each function it appears in". But I don't understand why it only applies to book.title yet other members in the struct remain unaffected.

#include<stdio.h>
#include<string.h>

struct LIS
{
  char title[75];
  char author[75];
  char borrower_name[75];
  int days_borrowed;
  float fine;
};

struct book;

void main() {

  int response;

  do {
    printf("Title of the book: ");
    gets(book.title);
    printf("Author(s) of the book: ");
    gets(book.author);
    printf("Name of borrower: ");
    gets(book.borrower_name);
    printf("Number of days borrowed: ");
    scanf("%d", &book.days_borrowed);
    if(book.days_borrowed > 3) { book.fine = 5.00 * (book.days_borrowed-3); }
    else { book.fine = 0; }

    printf("Fine (if applicable): %.2f\n", book.fine);

    printf("Enter any key continue/Enter 0 to end: ");
    scanf("%d\n", &response);
  } while (response != 0);

}

Solution

  • You should replace the code for book definition like this:

    struct LIS
    {
    char title[75];
    char author[75];
    char borrower_name[75];
    int days_borrowed;
    float fine;
    } book;
    

    or like this:

    struct LIS
    {
    char title[75];
    char author[75];
    char borrower_name[75];
    int days_borrowed;
    float fine;
    }; 
    struct LIS book;
    

    The variable book needs a structure type definition. Simply writing struct book; will not specify what kind of structure book is.


    Also, note that the function gets was removed from the C Standard, since it is not safe. Instead, you should use something like this:

    fgets(book.title,sizeof(book.title),stdin);