Error use of undeclared identifier true

Почему я получаю эту ошибку:... Вопрос о: c, ошибки компилятора.

Почему я получаю эту ошибку:

infinite.c:5:12: error: use of undeclared identifier 'true'
    while (true) {

1 error generated.
make: *** [infinite] Error 1

… когда я пытаюсь скомпилировать этот простой код для бесконечного цикла?

#include <stdio.h>

int main(void) {
    int x = 0;
    while (true) {
        printf("%in", x);
    }
}

4 ответы

Идентификатор true не объявляется по умолчанию. Чтобы использовать его, два решения:

  1. Скомпилируйте в C99 и включите <stdbool.h>.
  2. Определите этот идентификатор самостоятельно.

Однако бесконечный цикл for (;;) часто считается лучшим стилем.

Создан 10 ноя.

C не имеет встроенных логических типов. Так что не знает что true является. Вы должны объявить это самостоятельно следующим образом:

#define TRUE 1
#define FALSE 0

[...]
while (TRUE) {
     [...]
}

Создан 10 ноя.

Включите stdbool.h, чтобы использовать логические значения C99.
Если вы хотите придерживаться C89, определите его самостоятельно:

typedef enum
{
    true=1, false=0
}bool;

Создан 10 ноя.

Вы получаете эту ошибку, потому что вы не определили значения true и false в C. Вы можете сделать это, добавив несколько простых строк в свой код следующим образом:

#define FALSE 0
#define TRUE 1 // Option 1
#define TRUE !FALSE // Option 2

Создан 03 июля ’19, 06:07

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c
compiler-errors

or задайте свой вопрос.

Почему я получаю эту ошибку:

infinite.c:5:12: error: use of undeclared identifier 'true'
    while (true) {

1 error generated.
make: *** [infinite] Error 1

… когда я пытаюсь скомпилировать этот простой код для бесконечного цикла?

#include <stdio.h>

int main(void) {
    int x = 0;
    while (true) {
        printf("%in", x);
    }
}

person
gadgetmo
  
schedule
10.11.2012
  
source
источник

comment

Еще лучше: for (;;). Никаких тривиальных волшебных условий. И есть вероятность, что вы все равно можете вставить туда локальные объявления и условие выхода.
  —  person Kerrek SB    schedule 10.11.2012


Ответы (4)

Идентификатор true по умолчанию не объявлен. Для его использования есть два решения:

  1. Скомпилируйте в C99 и включите <stdbool.h>.
  2. Определите этот идентификатор самостоятельно.

Однако бесконечный цикл for (;;) часто считается лучшим стилем.

person
md5
  
schedule
10.11.2012

C не имеет встроенных логических типов. Так что он не знает, что такое true. Вы должны заявить об этом самостоятельно следующим образом:

#define TRUE 1
#define FALSE 0

[...]
while (TRUE) {
     [...]
}

person
Adam Sznajder
  
schedule
10.11.2012

comment

C имеет встроенный логический тип, он называется _Bool. Чтобы компилятор знал true и false, нужно #include <stdbool.h>, они не встроены, но тогда вы также можете использовать bool вместо _Bool (что немного некрасиво).
person Daniel Fischer; 10.11.2012

Включите stdbool.h, чтобы использовать логические значения C99.
Если вы хотите придерживаться C89, определите его самостоятельно:

typedef enum
{
    true=1, false=0
}bool;

person
Ramy Al Zuhouri
  
schedule
10.11.2012

comment

Если у вас нет stdbool.h, просто придерживайтесь того, что это будет делать, а именно дать определения препроцессору для этих значений, а не перечислений.
person Jens Gustedt; 10.11.2012

comment

Я думаю, что предпочтение определений препроцессора перед перечислениями или наоборот — это просто формальность в этих случаях.
person Ramy Al Zuhouri; 10.11.2012

Вы получаете эту ошибку, потому что вы не определили значения true и false в C. Вы можете сделать это, добавив несколько простых строк в свой код следующим образом:

#define FALSE 0
#define TRUE 1 // Option 1
#define TRUE !FALSE // Option 2

person
Batman
  
schedule
03.07.2019

Bug #80310 ext-intl with icu4c 68.1: use of undeclared identifier ‘TRUE’
Submitted: 2020-11-03 14:03 UTC Modified: 2020-11-03 15:09 UTC
From: me at derrabus dot de Assigned:
Status: Closed Package: Compile Failure
PHP Version: 7.4.12 OS: macOS 10.15
Private report: No CVE-ID: None

 [2020-11-03 14:03 UTC] me at derrabus dot de

Description:
------------
I tried to build php 7.4.12 with ext-intl against icu4c 68.1 and the compilation fails with the error output below. Downgrading to icu4c 67.1 fixes the problem.

This might be related to this change: https://unicode-org.atlassian.net/browse/ICU-21267

Actual result:
--------------
/path/to/php-7.4.12/ext/intl/collator/collator_sort.c:349:26: error: use of undeclared identifier 'TRUE'
        collator_sort_internal( TRUE, INTERNAL_FUNCTION_PARAM_PASSTHRU );
                                ^
/path/to/php-7.4.12/ext/intl/collator/collator_sort.c:543:26: error: use of undeclared identifier 'FALSE'
        collator_sort_internal( FALSE, INTERNAL_FUNCTION_PARAM_PASSTHRU );
                                ^
2 errors generated.
make: *** [ext/intl/collator/collator_sort.lo] Error 1
make: *** Waiting for unfinished jobs....

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports

 [2020-11-03 15:09 UTC] cmb@php.net

Would it work with

    CFLAGS=-DU_DEFINE_FALSE_AND_TRUE=1

 [2020-11-03 15:34 UTC] me at derrabus dot de

If I try this, the error is a different one, but it still does not compile.

/path/to/php-7.4.12/ext/intl/timezone/timezone_class.cpp:328:21: error: use of undeclared identifier 'FALSE'
        tz->getOffset(now, FALSE, rawOffset, dstOffset, uec);
                           ^
/path/to/php-7.4.12/ext/intl/timezone/timezone_methods.cpp:98:57: error: use of undeclared identifier 'FALSE'
        tz = timezone_convert_datetimezone(tzobj->type, tzobj, FALSE, NULL,
                                                               ^

 [2020-11-03 16:14 UTC] me at derrabus dot de

However, it *does* compile if I configure CXXFLAGS the same way.

 [2020-11-09 13:36 UTC] nikic@php.net

-Status: Open
+Status: Closed

One of the inherent problems with many programming languages is that compilers are often less than friendly when it comes to compiler messages. Not so with the Clang compiler – front end for C, C++, Objective-C and Objective-C++. Developed by Apple, this compiler actually produces messages the novice can understand. Consider the following piece of non-sensical code, containing a number of syntactic errors:

1  #include <stdio.h>
2
3  int main(void)
4  {
5      int anArray[n];
6      int i, n=10;
7      char aString[20];
8
9      scanf("%s", &aString);
10     i = 0;
11     while(true){
12         anArray[i] = 0
13     }
14     return 0;
15 }

When the code is compiled with gcc, we get the following messages:

$ gcc -Wall -std=c99 errors.c
errors.c: In function ‘main’:
errors.c:5: error: ‘n’ undeclared (first use in this function)
errors.c:5: error: (Each undeclared identifier is reported only once
errors.c:5: error: for each function it appears in.)
errors.c:9: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
errors.c:9: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
errors.c:11: error: ‘true’ undeclared (first use in this function)
errors.c:13: error: expected ‘;’ before ‘}’ token
errors.c:6: warning: unused variable ‘n’
errors.c:5: warning: unused variable ‘anArray’

Clearly from these error messages, there are issues with the code. Basically here are the actual problems with the syntax of the code:

  1. On line 5 of the code, n is used to size the integer array anArray, however n is not declared until line 6.
  2. On line 6, n is declared but never used.
  3. On line 9, the scanf() function uses an ampersand, &, before the string variable, which is redundant.
  4. On line 11, the variable true does not exist.
  5. On line 12, the statement is not terminated by a ;.

The inherent problem with gcc, and classically most compilers is that the error messages may not always be worded in the most appropriate way for novice programmers. That and no context is given, requiring the programmer to refer back to the code.

Here are the messages produced using Clang:

cc errors.c
errors.c:5:17: error: use of undeclared identifier 'n'
    int anArray[n];
                ^
errors.c:9:13: warning: format specifies type 'char *' but the argument has type
 'char (*)[20]' [-Wformat]
    scanf("%s", &aString);
           ~^ ~~~~~~~~
errors.c:11:11: error: use of undeclared identifier 'true'
    while(true){
          ^
1 warning and 2 errors generated.

Firstly, you’ll notice that this compiler has colour-coded the error messages. This makes it easier to differentiate errors from warnings. Secondly, it actually reproduces the offending code. This means the programmer does not need to refer back to the code in order to understand the problems. Thirdly, the source of the error on the line is pinpointed using the ^ character. Now not all the errors are shown, and that may be of benefit to the novice, as to not overwhelm them.

Fixing these 2 errors and the warning and re-compiling it results in the final problem being routed out:

errors.c:12:23: error: expected ';' after expression
    anArray[i] = 0
                  ^
                  ;
1 error generated.

A compiler well worth considering.

Понравилась статья? Поделить с друзьями:
  • Error using horzcat dimensions of arrays being concatenated are not consistent
  • Error using horzcat cat arguments dimensions are not consistent
  • Error use of undeclared identifier nullptr
  • Error using fprintf invalid file identifier use fopen to generate a valid file identifier
  • Error use of undeclared identifier itoa