Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit declaration of function 'gets' is invalid in C99

Tags:

c

Why am I getting this error?

implicit declaration of function 'gets' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

Code:

#include <stdio.h>
#include <stdlib.h>

typedef struct myStruct
{
    char name[20];
    char tel[20];
}contact;

int main(void)
{
    contact *mycont[3];

    for(int i=0; i<3; i++)
    {
        mycont[i] = (contact*)malloc(sizeof(contact));
        printf("Enter Name Of The Contact No.%d\n",i+1);
        gets(mycont[i]->name);
        printf("Enter The Contact Telephone Number\n");
        gets(mycont[i]->tel);
    }
}
like image 314
H. Jay Avatar asked Oct 15 '25 20:10

H. Jay


1 Answers

It's a safe bet that, even though the error message mentions C99, you are in fact using a compiler following a later standard, one in which gets was removed rather than just deprecated.

For example, when I try to compile the following simple program:

#include <stdio.h>
char buff[1000];
int main(void) {
    gets(buff);
    return 0;
}

with clang under Ubuntu 18.04:

clang -Werror --std=c11 -o qq qq.c

I get that same error:

qq.c:4:2: error: implicit declaration of function 'gets' is invalid in C99
                 [-Werror,-Wimplicit-function-declaration]

This is actually only tangentially related to the deprecation and removal of gets (in that it's no longer declared anywhere). It's more to do with the fact you shouldn't be trying to use any function without an active declaration, as per ISO C99 Foreword /5 (paraphrased):

This second edition cancels and replaces C90, as amended and corrected by various other ISO gumpf. Major changes from the previous edition include:

  • remove implicit function declaration.

  • lots of other stuff, irrelevant to this question.

You can see this if you replace gets with xyzzy, which results in the same error:

qq.c:4:2: error: implicit declaration of function 'xyzzy' is invalid in C99
                 [-Werror,-Wimplicit-function-declaration]

In fact, if you actually try to use gets with the C99 flags set, you'll get a totally different message (or none at all if your compiler implements C99 before they deprecated gets - that wasn't done until TC3):

qq.c:4:2: error: 'gets' is deprecated
                 [-Werror,-Wdeprecated-declarations]
like image 85
paxdiablo Avatar answered Oct 18 '25 11:10

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!