Error unterminated comment

в чем ошибка?? C++ Решение и ответ на вопрос 83080

0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

1

в чем ошибка??

06.01.2010, 16:05. Показов 4019. Ответов 19


здравствуйте, пытаюсь компилировать программу, но появляется сообщение об ошибке в строке
#include <iostream>

не подскажете, в чём дело.

ещё что-то не так с комментарием — unterminated comment
это значит, что он слишком длинный? )

я описывала эту программу здесь:

программа C++ для вычисления функции y=f(x)=arccot(x). всё ли правильно??

большое спасибо!!!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт JavaЭксперт С++

8378 / 3600 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

06.01.2010, 16:27

2

lilliputina, какой текст ошибки и какая среда?



0



0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

06.01.2010, 16:43

 [ТС]

3

text oshibki v 1-m sluchae: «invalid token» i «expected unqualified-id before numeric constant»

Bloodshed C++ Dev. 4.9.9.2



0



Эксперт JavaЭксперт С++

8378 / 3600 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

06.01.2010, 17:01

4

lilliputina, полный код выложи



0



lilliputina

0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

06.01.2010, 17:25

 [ТС]

5

вот я попробовала ещё в Code::Blocks 8.02

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    include <iostream>
 
using namespace std;
int main()
{
        /*
  Name: 
  Copyright:
  Author:
  Date: 06.01.10 14:29
  Description: Berechnet die Funktionswerte der inversen trigonometrischen Funktion y = f(x) = arccot(x), wenn |x|<1
  Fuer die Berechnung wird Summenformel p/2-(x-x3/3+ x5/5-x7/7+...+ (-1)n*x2n+1/2n+1+/-...)  verwendet
  Da "cmath" nicht anzuwenden sind, wurden zwei Hilfsfunktionen eingeführt:
            mypow (Potenzwert bilden)
             myabs (Betrag bilden).
*/
    double myabs(double input); double mypow(double basis, int exponent);
    int i;
 
    cout<< "x eingeben: ";
    cin>>x;
    if (myabs(x) < 1)
    {
    //Vorbelegung mit pi/2, erstes Glied der Summenformel
    summe_alt=pi_2;
    for (i=0; i<20; i++)
    {
     //weitere Glieder der Summenformel
    summe=summe_alt-(mypow(-1,i)*(mypow(x,2*i+1)/(2*i+1)));
    //Differenz von zi und zi+1
     if(myabs(summe-summe_alt)<epsilon) break;
    summe_alt=summe;
    }
 
    cout<<"narccot("<<x<<")="<<summe;
    }
    Else
    {
    //Benutzer hat ungueltige Eingabe gemacht (z.B. zu groß, zu klein etc.)
    cout<<"nBitte x innerhalb gueltiger Grenzen eingeben (|x|<1)!";
    }
 
     return 0;
     }
     //Funktion um Potenz zu berechnen
    double mypow(double basis, int exponent)
    {
    int i;
    double expwert=1;
 
    for (i=0; i<exponent; i++)
    expwert=expwert*basis;
 
    return expwert;
    }
 
    //Funktion um Betrag zu berechnen
    double myabs(double input)
    {
    if(input>0)
    return input;
    else
    return -input;
 
    //Benutzer hat ein x eingegeben
    cout<<x=0.5;
    cout<<y<<endl;
 
    return 0;
 }

такие ошибки:
1. syntax error before numeric constant
12. syntax error before numeric constant

как их исправить?



0



Эксперт JavaЭксперт С++

8378 / 3600 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

06.01.2010, 17:30

6

lilliputina, где # перед инклудом и почему функции внутри мейна описаны?



0



AnonymC

1183 / 468 / 87

Регистрация: 23.06.2009

Сообщений: 6,390

06.01.2010, 18:05

7

исправил код,и там ошибки

Error 1 error C2065: ‘x’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 15 h
Error 2 error C2065: ‘x’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 16 h
Error 3 error C2065: ‘summe_alt’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 19 h
Error 4 error C2065: ‘pi_2’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 19 h
Error 5 error C2065: ‘summe’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 23 h
Error 6 error C2065: ‘summe_alt’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 23 h
Error 7 error C2065: ‘x’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 23 h
Error 8 error C2065: ‘summe’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 25 h
Error 9 error C2065: ‘summe_alt’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 25 h
Error 10 error C2065: ‘epsilon’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 25 h
Error 11 error C2065: ‘summe_alt’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 26 h
Error 12 error C2065: ‘summe’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 26 h
Error 13 error C2065: ‘x’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 29 h
Error 14 error C2065: ‘summe’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 29 h
Error 15 error C2065: ‘Else’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 32 h
Error 16 error C2143: syntax error : missing ‘;’ before ‘{‘ c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 32 h
Error 17 error C2065: ‘x’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 60 h
Error 18 error C2065: ‘y’ : undeclared identifier c:documents and settingsagmy documentsvisual studio 2008projectshhh.cpp 61 h

код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
      double myabs(double input); double mypow(double basis, int exponent);
using namespace std;
int main()
{              
   
        int i;
 
        cout<< "x eingeben: ";
        cin>>x;
        if (myabs(x) < 1)
        {
        //Vorbelegung mit pi/2, erstes Glied der Summenformel
        summe_alt=pi_2;
        for (i=0; i<20; i++)
        {
         //weitere Glieder der Summenformel
        summe=summe_alt-(mypow(-1,i)*(mypow(x,2*i+1)/(2*i+1)));
        //Differenz von zi und zi+1
         if(myabs(summe-summe_alt)<epsilon) break;
        summe_alt=summe;
        }
 
        cout<<"narccot("<<x<<")="<<summe;
        }
        Else
        {
        //Benutzer hat ungueltige Eingabe gemacht (z.B. zu groЯ, zu klein etc.)
        cout<<"nBitte x innerhalb gueltiger Grenzen eingeben (|x|<1)!";
        }
 
         return 0;
}
         //Funktion um Potenz zu berechnen
        double mypow(double basis, int exponent)
        {
        int i;
        double expwert=1;
 
        for (i=0; i<exponent; i++)
        expwert=expwert*basis;
 
        return expwert;
        }
 
        //Funktion um Betrag zu berechnen
        double myabs(double input)
        {
        if(input>0)
        return input;
        else
        return -input;
 
        //Benutzer hat ein x eingegeben
        cout<<x=0.5;
        cout<<y<<endl;
 
        return 0;
        }

Добавлено через 32 секунды
у тебя не объявлены переменные и еще не Else a else



0



0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

06.01.2010, 18:07

 [ТС]

8

# перед инклудом и есть syntax error ? я ставила #, и компилятор указал на это как на 2-ю ошибку ( может, проблема в <iostream>?

функции внутри мейна почему-то не являются ошибкой ни в Bloodshed, ни в Blocks 8.02 ) спасибо, что вы мне на это указали!

18. int i — «syntax error before numeric constant»

i здесь тоже double?

Добавлено через 1 минуту
спасибо, МедведЪ !!



0



1183 / 468 / 87

Регистрация: 23.06.2009

Сообщений: 6,390

06.01.2010, 18:10

9

# перед инклудом и есть syntax error ? я ставила #, и компилятор указал на это как на 2-ю ошибку ( может, проблема в <iostream>?

что за ошибка



0



0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

06.01.2010, 19:04

 [ТС]

10

первая строка — ошибка:No such file or directory

using namespace std — syntax error before namespace ?

вы не могли бы подсказать, как декларировать cout и cin? везде писать ::std?



0



1183 / 468 / 87

Регистрация: 23.06.2009

Сообщений: 6,390

06.01.2010, 19:11

11

Цитата
Сообщение от lilliputina
Посмотреть сообщение

первая строка — ошибка:No such file or directory

не находит файл попробуйте iostream.h
сначала сделайте так,если первая ошибка пройдет то все пройдут вроде



0



0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

06.01.2010, 19:28

 [ТС]

12

с <iostream.h> не проходит )
не является ошибкой <stdio.h>, но опять нужно декларировать cout и cin
а как исправить » cout<<x=0.5; » ? syntax error before <<



0



M128K145

Эксперт JavaЭксперт С++

8378 / 3600 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

06.01.2010, 19:42

13

Вот

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
 
using namespace std;
double myabs(double input);
double mypow(double basis, int exponent);
int main()
{
    /*
    Name: 
    Copyright:
    Author:
    Date: 06.01.10 14:29
    Description: Berechnet die Funktionswerte der inversen trigonometrischen Funktion y = f(x) = arccot(x), wenn |x|<1
    Fuer die Berechnung wird Summenformel p/2-(x-x3/3+ x5/5-x7/7+...+ (-1)n*x2n+1/2n+1+/-...)  verwendet
    Da "cmath" nicht anzuwenden sind, wurden zwei Hilfsfunktionen eingefьhrt:
    mypow (Potenzwert bilden)
    myabs (Betrag bilden).
    */
    
    int i;
 
    double x, summe_alt, summe, pi_2, epsilon;
    cout<< "x eingeben: ";
    cin>>x;
    if (myabs(x) < 1)
    {
        //Vorbelegung mit pi/2, erstes Glied der Summenformel
        summe_alt=pi_2;
        for (i=0; i<20; i++)
        {
            //weitere Glieder der Summenformel
            summe=summe_alt-(mypow(-1,i)*(mypow(x,2*i+1)/(2*i+1)));
            //Differenz von zi und zi+1
            if(myabs(summe-summe_alt)<epsilon) break;
            summe_alt=summe;
        }
 
        cout<<"narccot("<<x<<")="<<summe;
    }
    else
    {
        //Benutzer hat ungueltige Eingabe gemacht (z.B. zu groЯ, zu klein etc.)
        cout<<"nBitte x innerhalb gueltiger Grenzen eingeben (|x|<1)!";
    }
 
    return 0;
}
//Funktion um Potenz zu berechnen
double mypow(double basis, int exponent)
{
    int i;
    double expwert=1;
 
    for (i=0; i<exponent; i++)
        expwert=expwert*basis;
 
    return expwert;
}
 
//Funktion um Betrag zu berechnen
double myabs(double input)
{
    if(input>0)
        return input;
    else
        return -input;
}

, проверил в деве



0



1183 / 468 / 87

Регистрация: 23.06.2009

Сообщений: 6,390

06.01.2010, 21:09

14

lilliputina, выложите весь код



0



lilliputina

0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

07.01.2010, 11:14

 [ТС]

15

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
 
using namespace std;
 
//Funktion um Potenz zu berechnen
double mypow(double basis, int exponent)
{
        int i;
        double expwert=1;
 
        for (i=0; i<exponent; i++)
                expwert=expwert*basis;
 
        return expwert;
}
 
//Funktion um Betrag zu berechnen
double myabs(double input)
{
        if(input>0)
                return input;
        else
                return -input;
}
 
int main()
{
        /*
        Name: 
        Description: Berechnet die Funktionswerte der inversen trigonometrischen Funktion y = f(x) = arccot(x), wenn |x|<1
        Fuer die Berechnung wird Summenformel p/2-(x-x3/3+ x5/5-x7/7+...+ (-1)n*x2n+1/2n+1+/-...)  verwendet
        Da "cmath" nicht anzuwenden sind, wurden zwei Hilfsfunktionen eingef?hrt:
        mypow (Potenzwert bilden)
        myabs (Betrag bilden).
        */
        
        int i;
 
        double x, y, summe_alt, summe, pi_2, epsilon;
        
        cout<< "x eingeben: ";
        cin>>x;
        if (myabs(x) < 1)
        {
                //Vorbelegung mit pi/2, erstes Glied der Summenformel
                summe_alt=pi_2;
                for (i=0; i<20; i++)
                {
                        //weitere Glieder der Summenformel
                        summe=summe_alt-(mypow(-1,i)*(mypow(x,2*i+1)/(2*i+1)));
                        //Differenz von zi und zi+1
                        if(myabs(summe-summe_alt)<epsilon) break;
                        summe_alt=summe;
                }
 
                cout<<"y= "<<"narccot("<<x<<")="<<summe; 
        }
        else
        {
                //Benutzer hat ungueltige Eingabe gemacht (z.B. zu gro?, zu klein etc.)
                cout<<"nBitte x innerhalb gueltiger Grenzen eingeben (|x|<1)!";
        }
 
        return 0;
}

в Dev++, ошибок нет. вроде бы работает ) спасибо вам за помощь!!! но может что-то ещё подкорректировать?



0



M128K145

Эксперт JavaЭксперт С++

8378 / 3600 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

07.01.2010, 14:23

16

lilliputina, я б твои функции так переписал бы

C++
1
2
3
4
5
6
7
8
9
10
11
double mypow(double basis, int exponent)
{
    double expwert = 1;
    while(exponent--)
        expwert *= basis;
    return expwert;
}
double myabs(double input)
{
    return input > 0 ? input : -input;
}



0



lilliputina

0 / 0 / 0

Регистрация: 01.01.2010

Сообщений: 10

07.01.2010, 16:04

 [ТС]

17

ага, спасибо!!! я ещё внесла исправления, а то у меня высчитывался арктангес, а не арккотангес )
теперь всё правильно

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
using namespace std;
 
//Funktion um Potenz zu berechnen
double mypow(double basis, int exponent)
{
    double expwert = 1;
    while(exponent--)
        expwert *= basis;
    return expwert;
}
 
//Funktion um Betrag zu berechnen
double myabs(double input)
{
    return input > 0 ? input : -input;
}
 
double mypow(double basis, int exponent);
double myabs(double input);
 
int main()
{
    /*
        Name: 
        Description: Berechnet die Funktionswerte der inversen trigonometrischen Funktion y = f(x) = arccot(x), wenn |x|<1
        Fuer die Berechnung wird Summenformel p/2-(x-x3/3 + x5/5 - x7/7+...+ (-1)n*x2n+1/2n+1+/-...)  verwendet
        Berechnung bricht ab, wenn die Differenz des Betrages zweier aufeinanderfolgender Glieder zi und zi+1 kleiner als ein zu definierender Abbruchwert epsilon wird oder wenn maximal 20 Summenglieder berechnet wurden
        Da "cmath" nicht anzuwenden sind, wurden zwei Hilfsfunktionen eingefuehrt:
        mypow (Potenzwert bilden)
        myabs (Betrag bilden)
        */
 
    //pi_2 ist PI/2, schon vorberechnet
    const double pi_2=1.5707963267948966192313216916398;
    double x, y, epsilon=0.000001, summe, summe_alt=0;
    int i;
 
    cout<<"x eingeben: ";
    cin>>x;
 
    if(myabs(x)<1)
    {
        //Vorbelegung mit pi/2, erstes Glied der Summenformel
        summe_alt=pi_2;
        for(i=0; i<20; i++)
        {
            //weitere Glieder der Summenformel
            summe=summe_alt-(mypow(-1,i)*(mypow(x,2*i+1)/(2*i+1)));
            //Differenz von zi und zi+1
            if(myabs(summe-summe_alt)<epsilon) break;
            summe_alt=summe;
        }
 
        cout<<"y= "<<"narccot("<<x<<")="<<summe;
    }
    else
    {
        //Benutzer hat ungueltige Eingabe gemacht
        cout<<"nBitte x innerhalb gueltiger Grenzen eingeben (|x|<1)!";
    }
 
    return 0;
}



0



Slav1991

0 / 0 / 2

Регистрация: 07.01.2010

Сообщений: 44

07.01.2010, 16:34

18

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{   const B=7,D=3.5;
    float AN,AK,HA,A,F,e,S,X;
    int K=0,CN,CK,HC,C;
    printf ("vvod AN-");
    scanf ("%f",&AN);
    printf ("vvod AK-");
    scanf ("%f",&AK);
    printf ("vvod HA-");
    scanf ("%d",&HA);
    printf ("vvod CN-");
    scanf ("%d",&CN);
    printf ("vvod CK-");
    scanf ("%d",&CK);
    printf ("vvod HC-");
    scanf ("%d",&HC);
    for (C=CN;C<=CK;C+=HC)
    X=0.01*HA;
    for (A=AN;A<=AK;A+=HA)
{   S=A*(D+B-C);
    printf ("S=%8.3f",S);}
if ((A>0)&&(A!=1)&&(C!=0))
{F=S/log10(A)*(pow(e,C-1));
printf ("F=%8.3f",F);}
else
printf ("F-net");
A=AN+HA;
getch();
}

Помогите исправить ошибки!Компилируется норм, а результат не выдает!!!!
A и C изменяемая величина в цикле(AN,CN-начальное;HA,HC-шаг;AK,CK-конечное) X-погрешность
S=A*(D+B-C)
F=S/log10(A)*(pow(e,C-1))



0



Эксперт С++

4725 / 2546 / 757

Регистрация: 18.08.2009

Сообщений: 4,568

07.01.2010, 16:58

19

Цитата
Сообщение от Slav1991
Посмотреть сообщение

const B=7,D=3.5;

Вот в этой строке, по умолчанию D присвоено будет значение 3.

Цитата
Сообщение от Slav1991
Посмотреть сообщение

float AN,AK,HA,A,F,e,S,X;

в этой строке переменной HA задаете тип float, а в этой:

Цитата
Сообщение от Slav1991
Посмотреть сообщение

scanf («%d»,&HA);

считаете что эта переменная int.

и задайте значение переменной e, ведь Вы ее используете в Ваших вычислениях.



0



0 / 0 / 2

Регистрация: 07.01.2010

Сообщений: 44

07.01.2010, 17:05

20

Спасибо!!!!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

07.01.2010, 17:05

Помогаю со студенческими работами здесь

В чем ошибка?По одной строке нормально в базу заходят,а две сразу вылетает ошибка?
INSERT INTO `jos_menu` (`id`, `menutype`, `name`, `alias`, `link`, `type`, `published`, `parent`,…

Реализовать через тип данных структура. При сборке и отладки возникает ошибка. В чем ошибка?
С++ в таблице из 5 строк хранятся данные о товарах: наименование, цена, количество. Определить и…

Ошибка 2 error LNK2019, не пойму в чем ошибка
Выдает такую ошибку: Ошибка 2 error LNK2019: ссылка на неразрешенный внешний символ &quot;int __cdecl…

В чем ошибка? При запуске программы открывается консоль и сразу ошибка о завершении программы
К тому же выдает warning: deprecated conversion from string constant to ‘char*’ .
#include…

ошибка вылетает в чем ошибка???
#include &quot;stdafx.h&quot;
#include &lt;stdio.h&gt;
#include &quot;math.h&quot;
#include &lt;conio.h&gt;

int main()

{…

Ошибка Для нестатического поля, метода или свойства «Rmas.msf» требуется ссылка на объект. Не пойму в чем ошибка?
CS0120 ошибка. Объявить класс, содержащий одномерный целочисленный массив размерностью 5,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

rdanler

New Member

  • Total Posts : 5
  • Reward points : 0
  • Joined: 2011/04/23 21:51:02
  • Location: 0
  • Status: offline

I have a curious problem that I can not find on the forums or on Google. I had about 20 C program in one project, all working OK. I updated the comment at the beginning of of each file to reflect the current date and rev. now all the files get a «Unterminated Comment» error, the comment beginning at line one. No amount of editing will make this problem go away. If I create a new file with a beginning comment it is OK. cutting and pasting the comment from the new file does not work. I suspect that something in the compiler or linker files is the real cause. Any suggestion appreciated.

Guest

Super Member

  • Total Posts : 80510
  • Reward points : 0
  • Joined: 2003/01/01 00:00:00
  • Location: 0
  • Status: online

Re:»Unterminated Comment» error


2012/03/21 17:46:10

(permalink)

Yes, the linker is the most suspect component!

eskopal

Super Member

  • Total Posts : 281
  • Reward points : 0
  • Joined: 2003/11/07 12:35:18
  • Location: Ossining, New York
  • Status: offline

Re:»Unterminated Comment» error


2012/03/21 20:28:13

(permalink)

Because it effects all files, the unterminated comment is probably in an «#include .h» file.

  ..Eugene..

rdanler

New Member

  • Total Posts : 5
  • Reward points : 0
  • Joined: 2011/04/23 21:51:02
  • Location: 0
  • Status: offline

Re:»Unterminated Comment» error


2012/03/21 21:33:47

(permalink)

 The error was in one of my .h files….Thanks for the great lead!!!

Common PHP 8.0 Compilation Error Messages

With PHP 8.0 closing on us, it is high time to check our code bases to see if they compile, at least. Here is a list of common PHP 8.0 compilation messages, and what do to with them.

The errors have been found on a corpus of 1756 PHP projects. Any emitted error was compared to the result of the PHP 7.4 compilation. This means that those errors are fatal in PHP 8, while they were absent, or a warning in PHP 7.4. In both cases, in PHP 7.4, it used to be possible to brush them under the carpet, but not in PHP 8.0 anymore.

Common PHP 8.0 compilation errors

  • Array and string offset access syntax with curly braces is no longer supported
  • Unparenthesized a ? b : c ? d : e is not supported. Use either (a ? b : c) ? d : e or a ? b : (c ? d : e)
  • __autoload() is no longer supported, use spl_autoload_register() instead
  • Cannot use ‘parent’ when current class scope has no parent
  • syntax error, unexpected ‘match’
  • The (real) cast has been removed, use (float) instead
  • The (unset) cast is no longer supported
  • Declaration of A2::B($c, $d = 0) must be compatible with A1::B(&$c, $d = 0)
  • Unterminated comment starting line

Array and string offset access syntax with curly braces is no longer supported

Array and string offset access syntax with curly braces is no longer supportedmeans that only the square bracket syntax is now valid.

 
<?php 
   $array = range(0, 10); 
  echo $array{3}; // 4 
?> 

Replace the { with [, and the code will be good again. Exakat spots those with the rule No more curly arrays.

Unparenthesized a ? b : c ? d : e is not supported. Use either (a ? b : c) ? d : e or a ? b : (c ? d : e)

Introduced in PHP 7.4, it is not possible to nest ternary operators. This is related to ternary being right associative, while most of the operators are left associative. PHP RFC: Deprecate left-associative ternary operators.

 
<?php 
1 ? 2 : 3 ? 4 : 5; // deprecated 
(1 ? 2 : 3) ? 4 : 5; // ok 
1 ? 2 : (3 ? 4 : 5); // ok 
?> 

The error message is quite verbose : take advantage of it! Add some parenthesis, or even , split the nested operation into independent expressions. Exakat spots those with the rule Nested Ternary Without Parenthesis.

__autoload() is no longer supported, use splautoloadregister() instead

This error message might appear here thanks to very old applications. Or if they try to support very old PHP versions. In any case, the message is self-explanatory.

Cannot use ‘parent’ when current class scope has no parent

Using the parent keyword in a class without parent, a.k.a. without extends keyword, used to be a Deprecation Notice. In fact, the class would blow up during execution with a ‘Cannot access parent:: when current class scope has no parent’ Fatal error.

It is now a Fatal error at linting time. This will shorten significantly the time between the bug creation and its discovery.

 <?php 
class x { 
   function foo() { 
      echo parent::a; 
   } 
}

(new x)->foo(); 
?> 

As for the fix, there are lots of options, depending on how this parent keyword ended up there in the first place. Exakat spots those with the rule Class Without Parent.

syntax error, unexpected ‘match’

This is a consequence of the introduction of the match instruction in PHP. It is not possible to use that name in instantiation (new), use expressions, instanceof, typehints, functions, classes, interfaces, traits or constants. It is still OK inside a namespace, or for a variable name.

 <?php

// This Match is still valid, thanks to the new Qualified Name processing 
use PeridotLeoMatcherMatch;

// This Match is invalid 
function foo(Match $match) { 
   // do something 
}

// Match side effect : syntax error, unexpected ',' 
$result = match($content,"'KOD_VERSION','(.*)'");

?>

When match is used as a function name, it may lead to an error about commas : the main argument of the new match keyword only accept one argument, so no comma.

The only solution is to rename the classes, interfaces, traits, functions or constants with another name and update the use expressions accordingly.

The (real) cast has been removed, use (float) instead

All is said here. (real) is gone, long live (float).

 
<?php 
  $price = (real) getActualPrice(); 
?> 

Just replace (real) by (float). While you’re at it, you can replace is_real() by is_float() : is_real() didn’t make it into PHP 8.0. Exakat spots those with the rule Avoid Real.

The (unset) cast is no longer supported

The big brother of the unset function is a type cast (unset). It used to be actually the typecast (null) (not in name, but in usage). Very little new about this, and it is a good thing : it is gone for good.

 
<?php 
   (unset) $foo; 
?> 

Exakat spots those with the rule Cast unset usage.

Declaration of A2::B($c, $d = 0) must be compatible with A1::B(&$c, $d = 0)

Checking for method compatibility used to be a warning in PHP 7, and it is now a Fatal error at linting time. The method signature in a parent and its child class must be compatible. It means a lot of different things, depending on visibility, reference, typehint, default values. It is worth a whole article by itself.

The important part is three folds : first, PHP 8.0 emits a Fatal error at compile time for that. So, your PHP 7.0 may hurt on 8.0. If you can fix it now.

 
<?php 
class A1 { 
   function B(&$c, $d = 0) {} 
}

class A2 extends A1 { 
  function B($c, $d = 0) {} 
}

?> 

The second important part is that it only works when PHP lints both classes (parent and child), in the same file, and in the right order : parent first, child second. Otherwise, PHP will only check the compatibility at execution time, and deliver a Fatal error at the worst moment.

The third important part is that compatibility between method signature doesn’t cover argument names. The following code is valid, and a major sleeping bug. Just notice that the variables have been swapped.

 
<?php 
class A1 { 
   function B($c, $d = 0) {} 
}

class A2 extends A1 { 
   function B($d, $c = 0) {} 
}

?> 

Exakat spots those with the following rules Incompatible Signature Methods, and Swapped arguments.

Unterminated comment starting line

Unterminated comment starting line used to be a warning. It is now a parse error.

 
<?php 
/** I always start, but never finish...

Just close the comment, and the code will be good again.

Compile with PHP 8.0 now!

PHP 8.0 moved a significant number of messages from Notice to Fatal errors, and, more importantly, from the execution phase to linting phase. This means that checking your current code with PHP 8.0 is sufficient to bring light on quirky pieces of code that will raise error when you want to upgrade to PHP 8.0. Simply fixing them will also improve your PHP 7.x code!

In the meantime, linting is as fast as it is superficial : it processes files individually, and postpone until execution some of the checks. Static analysis tools cover those situations, and report very early potential bugs and inconsistencies.

Install exakat and run the Migration audit on your code to get even better prepared for the Great Apparition of PHP 8.0. See you next month!

Понравилась статья? Поделить с друзьями:
  • Error unsupported type 51906
  • Error unsupported partition unaligned
  • Error unsupported operand types
  • Error unsupported opengl version sony vegas 13
  • Error unsupported dictionary type pcre