简体   繁体   中英

Why am I getting “error: use of undeclared identifier” error?

Summary

Error and code are at bottom of the question.

I was writing a simple program because I was curious what the size of pointers were and if they differed when they pointed to different data types.
I declared the variables, why are they saying they are undeclared?

Also, for some reason there is no error with the int* but only the bool* and char* as shown in the error message below.

Code

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

int main(void) {
    int* ptri = NULL;
    char* ptrc = NULL;
    bool* ptrb = NULL;
    printf("%lu %lu %lu", sizeof(ptri), sizeof(ptrc), sizeof(ptrb));
}

Error Message

:!clang test.c && ./a.out
test.c:7:5: error: use of undeclared identifier 'bool'
    bool* ptrb = NULL;
    ^
test.c:7:11: error: use of undeclared identifier 'ptrb'
    bool* ptrb = NULL;
          ^
test.c:8:62: error: use of undeclared identifier 'ptrb'
    printf("%lu %lu %lu", sizeof(ptri), sizeof(ptrc), sizeof(ptrb));
                                                             ^
3 errors generated.

shell returned 1

Declare #include <stdbool.h> into the header. It will work.Thanks.

The variables are fine (or would be if their declaration were not blocked by other errors).
You have a problem with the type identifier bool . It is not known by (old) standard C.
If you are used to using bool as a type please find out where that type is coming from in your successful other code.

C originally did not have native support for boolean values. In order to get the things working, you need to import a header file name <stdbool.h>

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    int* ptri = NULL;
    char* ptrc = NULL;
    bool* ptrb = NULL;
    printf("%lu %lu %lu", sizeof(ptri), sizeof(ptrc), sizeof(ptrb));
}

You should write this header " #include <stdbool.h>" which contains type bool

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

int main(void) {
    int* ptri = NULL;
    char* ptrc = NULL;
    bool* ptrb = NULL;
    printf("%lu %lu %lu", sizeof(int), sizeof(char), sizeof(bool));
}

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