简体   繁体   中英

implicit declaration of function 'GetInt' is invalid in C99

I am trying to make this simple code for practice in C. It asks the user to give a positive number, checks if it's positive or not, then returns just positive numbers.

I am getting this error:

positive.c:28:7: warning: implicit declaration of function 'GetInt' is invalid
  in C99 [-Wimplicit-function-declaration]
            n = GetInt();

I would have thought this meant I didn't declare one of my functions or that I didn't call in some library. To the best of my knowledge, I did all of this. Here is my code:

#include <stdio.h>

int GetPositiveInt(void);

int main(void)
{
    int n = GetPositiveInt();
    printf("Thanks for the %i\n", n);
}


/*This all gets called into the above bit*/
int GetPositiveInt(void)
{
    int n; /*declare the variable*/
    do
    {
        printf("Give me a positive integer: ");
        n = GetInt();
    }
    while (n <= 0);
    return n; /*return variable to above*/
}

Does anyone have any ideas on why this is giving me an error?

That's because this function, GetInt does not exist or you forgot to include the correct header.

You can replace the call to the function GetInt by:

scanf("%d", &n);

You haven't declared GetInt() . Compiler don't know what it returns and what arguments it receives. Implicit declarations was forbidden in C99 (was valid before - would only produce warning if you'll enable C89).

Of course if you'll have only declaration and no implementation - you'll get an error on linking phase.

There's a library created for the CS50 edX class you need to include at the top of your.c file. Otherwise the compiler doesn't know about the GetInt() function.

#include <cs50.h>

Worked for me: You may use get_int(); in the CS50 IDE and compile it using make or simply put -lcs50 at the end of clang.

The CS-50 library has been updated. Now you must use:

$ int x = get_int("Prompt: ");

instead of GetInt()

Your code will look like this:

#include <stdio.h>


int main(void)

{
    int n; /*declare the variable*/
    do
    {
        n = get_int(“Give me a positive integer: “);
    }
    while (n <= 0);
    return n; /*return variable to above*/
}

This worked for me. I'm also doing the CS50x 2023 Introduction to Computer Science.

Taken from the one of the "Shorts" Video, (Week 1: C). Conditional Statements

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

int main(void)
{
int x = get_int("Prompt: ");
switch(x)
  {
    case 5:
        printf("Five, ");
    case 4:
        printf("Four, ");
    case 3:
        printf("Three, ");
    case 2:
        printf("Two, ");
    case 1:
        printf("One, ");
    default:
        printf("Blast-off!\n");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM