Error initializer expression list treated as compound expression in initializer

I'm having an issue compiling the beginnings of a basic password protected file program, I'm getting the above error on line 11, (int login(username,password)). Not sure what's going on here, so it...

I’m having an issue compiling the beginnings of a basic password protected file program, I’m getting the above error on line 11, (int login(username,password)). Not sure what’s going on here, so it’d be nice if someone could shed some light on the situation.

#include <conio.h>
#include <iostream>
#include <string>

using namespace std;

int    i, passcount, asterisks;
char   replace, value, newchar;
string username, password, storedUsername, storedPassword;

int login(username, password);
{
    if (username == storedUsername) {
        if (password == storedPassword)
            cout << "Win!";
        else
            cout << "Username correct, password incorrect."
    } else
        cout << "Lose. Wrong username and password.";
}

int main() {
    cout << "Username: ";
    cin >> username;
    cout << "Password: ";
    do {
        newchar = getch();
        if (newchar == 13)
            break;
        for (passcount > 0; asterisks == passcount; asterisks++)
            cout << "*";
        password = password + newchar;
        passcount++;
    } while (passcount != 10);
    ifstream grabpass("passwords.txt") grabpass >> storedpass;
    grabpass.close();
    login(username, password);

    return 0;
}

I’m getting a C++ compiler error which I’m not familiar with. Probably a really stupid mistake, but I can’t quite put my finger on it.

Error:

test.cpp:27: error: member initializer expression list treated as compound expression
test.cpp:27: warning: left-hand operand of comma has no effect
test.cpp:27: error: invalid initialization of reference of type ‘const Bar&’ from expression of type ‘int’

Code:

  1 #include <iostream>
  2
  3 class Foo {
  4 public:
  5         Foo(float f) :
  6                 m_f(f)
  7         {}
  8
  9         float m_f;
 10 };
 11
 12 class Bar {
 13 public:
 14         Bar(const Foo& foo, int i) :
 15                 m_foo(foo),
 16                 m_i(i)
 17         {}
 18
 19         const Foo& m_foo;
 20         int m_i;
 21 };
 22
 23
 24 class Baz {
 25 public:
 26         Baz(const Foo& foo, int a) :
 27                 m_bar(foo, a)
 28         {}
 29
 30         const Bar& m_bar;
 31 };
 32
 33 int main(int argc, char *argv[]) {
 34         Foo a(3.14);
 35         Baz b(a, 5.0);
 36
 37         std::cout << b.m_bar.m_i << " " << b.m_bar.m_foo.m_f << std::endl;
 38
 39         return 0;
 40 }

Note:
It looks like the compiler is evaluating the commas in line 27 like here:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/co.htm

edit:
Okay, I understand the problem as Alan explained it. Now, for extra imaginary points, can someone explain how the compiler (g++) came up with the error message it gave?

asked May 18, 2009 at 10:41

Gilad Naor's user avatar

Gilad NaorGilad Naor

20.2k14 gold badges46 silver badges53 bronze badges

2

m_bar is a reference, so you can’t construct one.

As others have noted, you can initialise references with the object it refers to, but you can’t construct one like you’re trying to do.

Change line 30 to

const Bar m_bar

and it’ll compile / run properly.

answered May 18, 2009 at 10:56

Glen's user avatar

GlenGlen

21.5k3 gold badges61 silver badges76 bronze badges

m_bar is declared as a «const reference» and therefore can’t be instantiated with the constructor you’ve supplied.

Consider making m_bar a member, or passing a pre-constructed Bar object to the constructor.

answered May 18, 2009 at 10:46

Alan's user avatar

AlanAlan

13.5k9 gold badges43 silver badges50 bronze badges

You can see the problem much more clearly in the following code:

struct B {
    B( int a, int x  ) {}
};

int main() {
    const B & b( 1, 2);
}

which produces the following errors with g++:

t.cpp: In function 'int main()':
t.cpp:6: error: initializer expression list treated as compound expression
t.cpp:6: error: invalid initialization of reference of type 'const B&' from expression of type int'

VC++ 6.0 gives the even more gnomic error:

 error C2059: syntax error : 'constant'

Simply put, you can’t initialise references like that.

answered May 18, 2009 at 11:13

(Edit: See the comments)
Although this question is old, for future readers I will point out that the item marked as an answer is not correct. A reference can indeed be constructed.

In an initializer line, the code m_bar(foo, a) is trying to use (foo,a) as a constructor for m_bar. The error tells you that foo will be ignored and you can’t construct a Bar out of int a. The following correct syntax will compile error free:

m_bar (*new Bar(foo,a))

answered Feb 21, 2014 at 7:14

Tod's user avatar

TodTod

8,1645 gold badges51 silver badges91 bronze badges

2

Содержание

  1. Ошибка при вызове функции с использованием указателей в качестве параметра
  2. Решение
  3. Другие решения
  4. Thread: error: initializer expression list treated as compound expression
  5. error: initializer expression list treated as compound expression
  6. Error initializer expression list treated as compound expression in initializer
  7. Ошибка C ++ — «список выражений инициализатора членов обрабатывается как составное выражение»
  8. 4 ответы
  9. wchar.h errors
  10. Re: wchar.h errors
  11. Re: wchar.h errors

Ошибка при вызове функции с использованием указателей в качестве параметра

Сообщение об ошибке:

В строке 39 моего кода я вызываю функцию concat; Я никогда не видел эту ошибку раньше, и я не знаю, как ее исправить.

Решение

Это запутывает синтаксис для объявление переменной а также вызов функции. Чтобы избежать путаницы, вы должны выбрать другое имя для переменной и инициализировать его в результате вызова функции.

Это должно исправить первую ошибку; вторая причина в том, что первый и третий аргументы должны быть указателями; но вы разыменовываете указатели, чтобы получить int ценности, на которые они указывают.

Так что это должно быть что-то вроде

Будем надеяться, что вскоре вы поймете, почему плохая идея манипулировать такими указателями, как исправить утечку памяти в вашем коде и как использовать библиотечные средства для более легкого управления памятью. Но это скорее выходит за рамки вопроса.

Другие решения

Фактически это выглядит как определение указателя на int с именем concatArray и с некоторыми аргументами.

Более того, если вы имели в виду вызов функции concatArray и если бы вы написали правильно

тем не менее, его каллусы также недействительны, потому что вместо указателей вы передаете в качестве аргументов объекты типа int: * pArray1 и * pArray2.

Примите во внимание, что размеры массивов должны быть константными выражениями в C ++. Итак, этот код

Источник

Thread: error: initializer expression list treated as compound expression

Thread Tools
Search Thread
Display

error: initializer expression list treated as compound expression

Hi all,
i would like to say thank you for this forum to provide many facility for us.

i have code in c++ with gsl library to calculate the regression. but i can not run it there is error says:
initializer expression list treated as compound expression
and i do not know how to avoid it. please guys i need your help.
the code is:

#include
#include
#include
#include
#include
using namespace std;

double reg(int n, int p, double *mo, double *pg, double *l, double *ll)
<
double store[p];
gsl_multifit_linear_workspace *ws;
gsl_matrix *cov, *X;
gsl_vector *y, *c;
double chisq;
int i, j;
X = gsl_matrix_alloc(n, p);
y = gsl_vector_alloc(n);
c = gsl_vector_alloc(p);
cov = gsl_matrix_alloc(p, p);
for(i=0; i

First, indent your code.
Second, you never actually call reg. Remove the «double» to do a function call.
As for the error, it’s because you try to create an array with a non-constant variable as the size parameter. This is illegal in C++.

Example:
int n= 10;
int arr[n]; // Illegal

const int n = 10;
int arr[n]; // OK
int arr[10]; // OK

You can use std::vector instead:

int n = 10;
std::vector arr(n); // OK

You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

Outside of your DOS world, your header file is meaningless.

Источник

Error initializer expression list treated as compound expression in initializer

3 weeks ago and I’m only doing it for the learning aspect.

I’m trying to make the program push an element to the front of a doubly linked list then print backwards. The problem is it works for printing the list when starting at the beginning but not when starting at the end. What am I doing wrong?

Output: (I bolded the part that applies to this question)

Problem Function (I think):

There are two files: Main.cpp and DoublyLinkedList.h

Help would be greatly appreciated, thanks!

head->next is the ACTUAL front node. Head is just the pointer.

Why? If ‘head’ were «just a pointer«, then it would not have member ‘next’.

keskiverto wrote:
Why? If ‘head’ were «just a pointer», then it would not have member ‘next’.

Thanks for your reply! That was a note to self and I meant it’s a pointer from the class:

Apologies for the confusion, I thought about removing my comments but figured it may be good to have you all see my thought process.

To clarify, I have a few questions:
Your code shows:

And my class shows:

— — —
Other than my questions above, your solution makes sense. Unfortunately, for some reason my new code is giving errors after I made the changes.

I looked it up and I know error: new initializer expression list treated as compound expression was because it didn’t include a data type. So I added the int to data and that made 1 less error appear. But I don’t know what datatype nullptr would be.

Main.cpp is the same.

DoublyLinkedList.h: http://www.cpp.sh/4yaerl
(The function is on line 71)

The nullptr has specific pointer type.
The NULL is a macro, like you would write .

It is (usually) a good habit to initialize variables, particularly pointers.

I wrote 42 , not int 42 .

You can either use aggregate initialization:
head = new Int_Node2 < data, nullptr , nullptr >;
or provide a constructor:

Thanks for your reply!

keskiverto wrote:
The nullptr has specific pointer type.
The NULL is a macro, like you would write .

Ah okay, I don’t have a lot of experience with macros.

keskiverto wrote:
It is (usually) a good habit to initialize variables, particularly pointers.

Ah, I’ve heard a lot of different people say a lot of different things for this. I started doing things like int num = 0; or std::string str1 = «» ; , then people told me on the cplusplus forums that there’s no need to do that because they are set to that by default. So I stopped doing that and now someone tells me it’s a good habit. Haha..

keskiverto wrote:
I wrote 42, not int 42.

My response from above explained why I wrote int data rather than just data :

PiggiesGoSqueal wrote:
I looked it up and I know error: new initializer expression list treated as compound expression was because it didn’t include a data type. So I added the int to data and that made 1 less error appear. But I don’t know what datatype nullptr would be.

In other words, when I had it only has data another error appeared.

I removed the «int» from int data and got these errors:

keskiverto wrote:
You can either use aggregate initialization:
head = new Int_Node2 < data, nullptr , nullptr >;

or provide a constructor:

Well, I’m thoroughly confused now. Okay, so was the first comment of head = new Int_Node2 ( data, nullptr , nullptr ); assumed I would add a constructor too? And I didn’t which is why I got an error, yes?

Then the aggregate initialization method only requires that single line to work, yes?

I tried both methods. The aggregate initialization method gave a Segmentation fault when ran.

Here’s the setup for that:

Then I commented out that line and tried with the constructor:
— Here is the part for the struct code:

— Here is the part for the actual member function:

Источник

Ошибка C ++ — «список выражений инициализатора членов обрабатывается как составное выражение»

Я получаю ошибку компилятора C ++, с которой я не знаком. Вероятно, действительно глупая ошибка, но я не могу понять ее.

редактировать: Хорошо, я понимаю проблему, как ее объяснил Алан. Теперь, что касается дополнительных воображаемых моментов, может ли кто-нибудь объяснить, как компилятор (g ++) выдал сообщение об ошибке, которое он выдал?

задан 18 мая ’09, 07:05

Как в g ++ появилось сообщение об ошибке? Без понятия. Sun Studio выдает эту ошибку в строке 27: Ошибка: слишком много инициализаторов для m_bar. Это немного информативнее. Короткий ответ заключается в том, что многие сообщения об ошибках компилятора, как правило, трудно читать. — Glen

За дополнительные баллы: Эта ошибка возникла из-за того, что код пытается построить Bar с конструктором (foo,a) . Сообщение об ошибке сообщает вам, что foo будет проигнорирован и что он не может преобразовать int a в бар. Я знаю, что это древний вопрос, но то, что вы отметили как ответ, неверно и вводит в заблуждение. Я разместил код того, как вы оставите свое заявление m_bar в одиночку и заставьте это скомпилировать. — Tod

4 ответы

m_bar — это ссылка, поэтому вы не можете создать ее.

Как отмечали другие, вы можете инициализировать ссылки с помощью объекта, на который они ссылаются, но вы не можете создать его, как вы пытаетесь это сделать.

Измените строку 30 на

и он будет правильно компилироваться / работать.

ответ дан 18 мая ’09, 11:05

m_bar объявлен как «константная ссылка» и поэтому не может быть создан с помощью предоставленного вами конструктора.

Подумайте о том, чтобы сделать m_bar членом или передать конструктору предварительно созданный объект Bar.

ответ дан 18 мая ’09, 11:05

Вы можете более четко увидеть проблему в следующем коде:

который вызывает следующие ошибки с g ++:

VC ++ 6.0 дает еще более гномическую ошибку:

Проще говоря, вы не можете инициализировать такие ссылки.

ответ дан 18 мая ’09, 12:05

Хотя это старый вопрос, для будущих читателей я укажу, что пункт, отмеченный как ответ, неверен. Ссылка действительно может быть создана.

В строке инициализатора код m_bar(foo, a) пытается использовать (foo,a) как конструктор для m_bar. Ошибка сообщает вам, что foo будут проигнорированы, и вы не сможете построить Бар из int a . Следующий правильный синтаксис будет компилировать без ошибок:

Ответ, помеченный как правильный, безусловно, правильный! Хотя ссылка может быть построенным, это не значит должен! (Хотя в отношении сообщения компилятора вы на правильном пути, я согласен!) — Тройсеф

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

Источник

wchar.h errors

День добрый. У меня Ubuntu 8.04 64-bit, libc6-dev версии 2.7-10. Проблема в том что при компиляции любой программы использующей например iostream.h, которая в свою очередь подключает wchar.h, получаем следуещее:

[code] /usr/include/wchar.h:527: error: expected initializer before ‘*’ token /usr/include/wchar.h:534: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:534: error: ‘__fp’ was not declared in this scope /usr/include/wchar.h:534: error: expected primary-expression before ‘int’ /usr/include/wchar.h:534: error: initializer expression list treated as compound expression /usr/include/wchar.h:534: error: expected ‘,’ or ‘;’ before ‘throw’ /usr/include/wchar.h:541: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:541: error: expected primary-expression before ‘__restrict__’ /usr/include/wchar.h:542: error: expected primary-expression before ‘const’ /usr/include/wchar.h:542: error: expected primary-expression before ‘. ’ token /usr/include/wchar.h:542: error: initializer expression list treated as compound expression /usr/include/wchar.h:559: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:559: error: expected primary-expression before ‘__restrict__’ /usr/include/wchar.h:560: error: expected primary-expression before ‘const’ /usr/include/wchar.h:561: error: expected primary-expression before ‘__arg’ /usr/include/wchar.h:561: error: initializer expression list treated as compound expression /usr/include/wchar.h:582: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:582: error: expected primary-expression before ‘__restrict__’ /usr/include/wchar.h:583: error: expected primary-expression before ‘const’ /usr/include/wchar.h:583: error: expected primary-expression before ‘. ’ token /usr/include/wchar.h:583: error: initializer expression list treated as compound expression /usr/include/wchar.h:636: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:636: error: expected primary-expression before ‘__restrict__’ /usr/include/wchar.h:637: error: expected primary-expression before ‘const’ /usr/include/wchar.h:638: error: expected primary-expression before ‘__arg’ /usr/include/wchar.h:638: error: initializer expression list treated as compound expression /usr/include/wchar.h:692: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:692: error: ‘__stream’ was not declared in this scope /usr/include/wchar.h:693: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:693: error: ‘__stream’ was not declared in this scope /usr/include/wchar.h:706: error: ‘__FILE’ has not been declared /usr/include/wchar.h:707: error: ‘__FILE’ has not been declared /usr/include/wchar.h:722: error: ‘__FILE’ has not been declared /usr/include/wchar.h:729: error: ‘__FILE’ has not been declared /usr/include/wchar.h:736: error: ‘__FILE’ has not been declared /usr/include/wchar.h:748: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:748: error: ‘__stream’ was not declared in this scope /usr/include/wchar.h:757: error: ‘__FILE’ was not declared in this scope /usr/include/wchar.h:757: error: ‘__stream’ was not declared in this scope /usr/include/wchar.h:765: error: ‘__FILE’ has not been declared /usr/include/wchar.h:774: error: ‘__FILE’ has not been declared /usr/include/wchar.h:785: error: ‘__FILE’ has not been declared /usr/include/wchar.h:794: error: ‘__FILE’ has not been declared [/code]

Переустановка вышеупомянутого пакета libc6-dev содержащего данный файл заголовков ничего не дала. Есть идеи?

Re: wchar.h errors

iostream.h уже давно deprecated.
Пользуй iostream.
«iostream содержит щаблоны классы, которые поддерживают как обычные символы (char), так и «широкие» юникодные (wchar_t). iostream.h поддерживает только обычные символы.» (c) не мой.

Re: wchar.h errors

Это все конечно прекрасно, но когда программа в сырцах не буду ж я их переписывать. А пользую таки iostream, но эффект тот же. Никаких тебе cout и cin

Например код: #include int main()< cout >> «Preved»; return 0; >

Источник

  • Forum
  • Beginners
  • error: expression list treated as compou

error: expression list treated as compound expression in mem-initializer

Hello again, I’m trying to make a linked list that stores a bunch of shape objects that I created. The shape class is an abstract base class since it’s being used as a parent class to a variety of other shape objects — but I’ve omitted them since they shouldn’t pertain to this question.

My main question was in Picture’s constructor, the compiler is giving me the error: error: expression list treated as compound expression in mem-initializer [-fpermissive].

It appears I’m getting tons of errors just coming from this one class and struct so I pasted my whole class just in case someone sees something that I didn’t write correctly. I suspect all the errors I’m getting are a result of sloppy implementation in all areas on my part.

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
#include "Shape.cpp"

class Picture{
    
    public:
        Picture():head(0,0){} // remember to look at your node class and see how many parameters need to be passed to intialize a node
        //you can ONLY have pointers and references to an abstract base class
        
        void insert(Shape *s){head = new ShapeNode(s,head);}
        
        double totalArea()
        {
            double total = 0.0;
            for(ShapeNode p = head; p != 0; p = p->next)
            {
                total += p->info->area();
            }
            return total;
        }
    
    private:
    struct ShapeNode
    {
        Shape *info;
        ShapeNode *next;
        ShapeNode(Shape *newInfo, ShapeNode *newNext) : info(newInfo),next(newNext){}
    };
    ShapeNode *head;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
class Shape {
protected:
  double xCoord,yCoord;
  //third member
public:
	Shape(double x = 0, double y = 0) : xCoord(x),yCoord(y){};
	virtual double getX();
	virtual double getY();
  	virtual double area() = 0;
  	virtual void draw() const = 0;
  	
  	virtual ~Shape();
};

head is a pointer, you can’t pass two values to a pointer.

weird, I was talking to someone about that earlier since before I had it as

before and it was giving me errors, I don’t know why reversing the change doesn’t give me back the same error, though I did change a few things

Last edited on

Topic archived. No new replies allowed.

Сообщение об ошибке:

main.cpp: In function 'int main()':
main.cpp:39:52: error: expression list treated as compound expression in initializer [-fpermissive]
int* concatArray (*pArray1, size1, *pArray2, size2);
^
main.cpp:39:52: error: invalid conversion from 'int' to 'int*' [-fpermissive]

В строке 39 моего кода я вызываю функцию concat; Я никогда не видел эту ошибку раньше, и я не знаю, как ее исправить.

#include <iostream>
#include <cstdlib>

using namespace std;

int* concatArray (int* pArray1, int size1, int* pArray2, int size2);

int main (){

int size1 = 8;
int Array1 [size1];
for (int i = 0; i < size1; i++){
Array1[i] = rand() % 10;
}

int size2 = 10;
int Array2 [size2];
for (int i = 0; i < size2; i++){
Array2[i] = rand() % 10;
}

int* pArray1;
int* pArray2;
pArray1 = Array1;
pArray2 = Array2;

cout << "The first array contains: " << endl;
for (int i = 0; i < size1; i++){
cout << Array1[i] << endl;
}

cout << "The second array contains: " << endl;
for (int i = 0; i < size2; i++){
cout << Array2[i] << endl;
}

int* concatArray (*pArray1, size1, *pArray2, size2);

cout << "the concat array contains: " << endl;
for (int i = 0; i < size1 + size2; i++) {
cout << (concatArray + i) << endl;
}
return 0;
}

int* concatArray (int* pArray1, int size1, int* pArray2, int size2){

int* concatArray = new int [size1 + size2];
for (int i = 0; i < size1 + size2; i++) {
if(i < size1){
*(concatArray + i) = *(pArray1 + i);
}
else{
*(concatArray + i) = *(pArray2 + i);
}
}
return concatArray;
}

0

Решение

int* concatArray (*pArray1, size1, *pArray2, size2);

Это запутывает синтаксис для объявление переменной а также вызов функции. Чтобы избежать путаницы, вы должны выбрать другое имя для переменной и инициализировать его в результате вызова функции.

Это должно исправить первую ошибку; вторая причина в том, что первый и третий аргументы должны быть указателями; но вы разыменовываете указатели, чтобы получить int ценности, на которые они указывают.

Так что это должно быть что-то вроде

int* concatenated = concatArray(pArray1, size1, pArray2, size2);

Будем надеяться, что вскоре вы поймете, почему плохая идея манипулировать такими указателями, как исправить утечку памяти в вашем коде и как использовать библиотечные средства для более легкого управления памятью. Но это скорее выходит за рамки вопроса.

3

Другие решения

Это выражение

int* concatArray (*pArray1, size1, *pArray2, size2);

является недействительным.

Фактически это выглядит как определение указателя на int с именем concatArray и с некоторыми аргументами.

Более того, если вы имели в виду вызов функции concatArray и если бы вы написали правильно

int *SomePointer = concatArray (*pArray1, size1, *pArray2, size2);

тем не менее, его каллусы также недействительны, потому что вместо указателей вы передаете в качестве аргументов объекты типа int: * pArray1 и * pArray2.

Примите во внимание, что размеры массивов должны быть константными выражениями в C ++. Итак, этот код

int size1 = 8;
int Array1 [size1];
//...
int size2 = 10;
int Array2 [size2];

не совместим с C ++.

Также этот цикл в функции

for (int i = 0; i < size1 + size2; i++) {
if(i < size1){
*(concatArray + i) = *(pArray1 + i);
}
else{
*(concatArray + i) = *(pArray2 + i);
}
}

является недействительным. Вместо

*(concatArray + i) = *(pArray2 + i);

там должен быть

*(concatArray + i) = *(pArray2 + i - size1);

0

  • Home
  • Forum
  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk
  • [SOLVED] C++ error: «expression list treated as compound expression»

  1. [solved] C++ error: «expression list treated as compound expression»

    Hi, I new to C++, and I am trying to use the gsl libraries for scientific computation. I keep encountering this error while trying to do a simple example of integration:

    Code:

    integral.cpp: In function �int main()�:
    integral.cpp:23: error: initializer expression list treated as compound expression

    Here is the program I have written to do a simple integration:

    Code:

    #include <iostream>
    #include <cmath>
    #include <gsl/gsl_integration.h>
    using namespace std;
    
    double f(double x, void * params);
    
    int main(){
      double result, error;
      int numberEvals;
      double a=1;
    
      gsl_function F;
      F.function = &f; // F.function is pointed to the address of f
      F.params = &a;   // F.params is pointed to the address of a
    
      int gsl_integration_qng(&F, 0, 1, 0, 1e-7, &result, &error, numberEvals);
    
      cout<<"result="<<result<<endl;
      cout<<"error="<<error<<endl;
      cout<<"numberEvals="<<numberEvals<<endl;
    
      return 0;
    }
    
    double f(double x, void * params){
      // params is a pointer to a void variable
      double a=*(double *) params;   
      cout<<"a="<<a<<endl;
      return a*pow(x,2);

    Line 23 of my code is the one that begins int gsl_integration_qng

    I have already tried adding #include <stdint.h>, as suggested in another post about compile errors.

    I am using the g++ compiler on Ubuntu.

    I would really appreciate any help anyone can give me!

    Last edited by adasilva; June 30th, 2010 at 03:14 PM.

    Reason: solved the problem.


  2. Re: C++ error: «expression list treated as compound expression»

    You shouldn’t reuse function names as variable names.


  3. Re: C++ error: «expression list treated as compound expression»

    Thanks for the reply, but I don’t think I have reused a function name as a variable name. Are you refering to the
    As I understand it, I have only referenced the memory address of the function. Is this enough to give an error?

    If so, do you have a suggestion of how I can refer to the function? This is how it is done in the documentation (see http://www.gnu.org/software/gsl/manu…-examples.html).


  4. Re: C++ error: «expression list treated as compound expression»

    Quote Originally Posted by adasilva
    View Post

    Code:

      int gsl_integration_qng(&F, 0, 1, 0, 1e-7, &result, &error, numberEvals);

    you have to name a variable. eg:

    Code:

    int result = gsl_integration_qng(&F, 0, 1, 0, 1e-7, &result, &error, numberEvals);


  5. Re: C++ error: «expression list treated as compound expression»

    http://www.network-theory.co.uk/docs…tegration.htmlFunction: int gsl_integration_qng (const gsl_function * f, double a, double b, double epsabs, double epsrel, double * result, double * abserr, size_t * neval)


  6. Re: C++ error: «expression list treated as compound expression»

    Thanks, your responses helped me to fix that error. It also turned out that I needed to link the gsl and cblas libraries using

    Code:

    g++ -o filename_of_executable -lgsl -lcblas filename.cpp


Tags for this Thread

Bookmarks

Bookmarks


Posting Permissions

Old

11-14-2007

72,
0

Member Information Avatar

Join Date: Sep 2007

Last Activity: 7 October 2015, 7:09 AM EDT

Posts: 72

Thanks Given: 0

Thanked 0 Times in 0 Posts

ok………..here is the section of my code……….

from main I am Calling function…….
setup_ipc(«msqueue»,1234,INPUT_IPC,LARGE_QUEUE);
and its defination is in another *.cpp file

and here is its defination
int setup_ipc (const char * ipc_name, long base_add, int io_type, int ipc_qtype)
{
char sbuffer[FILENAMELEN + 1];
key_t msg_key;
int msg_flag;
if ((io_type != INPUT_IPC && io_type != OUTPUT_IPC) ||
(ipc_qtype != SMALL_QUEUE && ipc_qtype != LARGE_QUEUE &&
ipc_qtype != PRI_QUEUE && ipc_qtype != MAIL_BOX &&
ipc_qtype != SOCKET_QUEUE)) {return(-1);}

if (!(*ipc_name)) {return(-1);}

/** look for the end of ipc_tbl **/
lipc_tbl = &ipc_lhead;
for (ipc_tbl = ipc_lhead.ipc_nextent; ipc_tbl;lipc_tbl = ipc_tbl, ipc_tbl = ipc_tbl->ipc_nextent);

ipc_tbl = (struct ipc_ent *) malloc(sizeof(struct ipc_ent));
if ( !ipc_tbl ) {return(-1);}

/** init table entry variables **/
strncpy(sbuffer, ipc_name, FILENAMELEN);
sbuffer[FILENAMELEN — 1] = »;
sprintf(ipc_tbl->fname, «%s», sbuffer);
ipc_tbl->ipc_tag = ++ipc_ecnt;
ipc_tbl->io_type = io_type;
ipc_tbl->vlmsg_id = -1;
ipc_tbl->sockfd = -1;
ipc_tbl->vlkey_id = base_add;
ipc_tbl->qtype = ipc_qtype;
ipc_tbl->ipc_nextent = NULL;

/** open message queue **/
if (ipc_qtype != SOCKET_QUEUE)
{
msg_key = ipc_tbl->vlkey_id;
if (io_type == INPUT_IPC)
msg_flag = IPC_CREAT | IPC_EXCL | 0666;
else
msg_flag = 0666;

errno = 0;
while ((ipc_tbl->vlmsg_id = msgget(msg_key, msg_flag)) < 0 && errno == EEXIST)
{
errno = 0;
msg_key++;
}

if (errno != 0)
{ // error other than EEXIST occurs
free(ipc_tbl);
return(-1);
}

ipc_tbl->vlkey_id = msg_key;
}

Я получаю ошибку компилятора С++, с которой я не знаком. Наверное, действительно глупая ошибка, но я не могу на нее положиться.

Ошибка:

test.cpp:27: error: member initializer expression list treated as compound expression
test.cpp:27: warning: left-hand operand of comma has no effect
test.cpp:27: error: invalid initialization of reference of type ‘const Bar&’ from expression of type ‘int’

код:

  1 #include <iostream>
  2
  3 class Foo {
  4 public:
  5         Foo(float f) :
  6                 m_f(f)
  7         {}
  8
  9         float m_f;
 10 };
 11
 12 class Bar {
 13 public:
 14         Bar(const Foo& foo, int i) :
 15                 m_foo(foo),
 16                 m_i(i)
 17         {}
 18
 19         const Foo& m_foo;
 20         int m_i;
 21 };
 22
 23
 24 class Baz {
 25 public:
 26         Baz(const Foo& foo, int a) :
 27                 m_bar(foo, a)
 28         {}
 29
 30         const Bar& m_bar;
 31 };
 32
 33 int main(int argc, char *argv[]) {
 34         Foo a(3.14);
 35         Baz b(a, 5.0);
 36
 37         std::cout << b.m_bar.m_i << " " << b.m_bar.m_foo.m_f << std::endl;
 38
 39         return 0;
 40 }

Примечание: Похоже, компилятор оценивает запятые в строке 27, как здесь:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/co.htm

изменить
Хорошо, я понимаю проблему, как объяснил Алан. Теперь, для дополнительных мнимых точек, может кто-нибудь объяснить, как компилятор (g++) пришел с сообщением об ошибке, которое он дал?

i have code in c++ with gsl library to calculate the regression. but i can not run it there is error says:
initializer expression list treated as compound expression
and i do not know how to avoid it…..please guys i need your help.
the code is:

#include <iostream>
#include <stdio.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
using namespace std;

double reg(int n, int p, double *mo, double *pg, double *l, double *ll)
{
double store[p];
gsl_multifit_linear_workspace *ws;
gsl_matrix *cov, *X;
gsl_vector *y, *c;
double chisq;
int i, j;
X = gsl_matrix_alloc(n, p);
y = gsl_vector_alloc(n);
c = gsl_vector_alloc(p);
cov = gsl_matrix_alloc(p, p);
for(i=0; i < n; i++)
{
gsl_matrix_set(X, i, 0, 1.0);
gsl_matrix_set(X, i, 1, mo[i]);
gsl_matrix_set(X, i, 2, pg[i]);
gsl_matrix_set(X, i, 3, l[i]);
gsl_vector_set(y, i, ll[i]);
}
ws = gsl_multifit_linear_alloc(n, p);
gsl_multifit_linear(X, y, c, cov, &chisq, ws);
/* store result … */
for(i=0; i < p; i++)
{
store[i] = gsl_vector_get(c, i);
}
gsl_multifit_linear_free(ws);
gsl_matrix_free(X);
gsl_matrix_free(cov);
gsl_vector_free(y);
gsl_vector_free(c);
return *store; /* we do not «analyse» the result (cov matrix mainly)
to know if the fit is «good» */
}

int main ()
{
int pixel = 4, parameter=4;
gsl_vector* st;
st = gsl_vector_alloc (parameter);
gsl_vector_free (st);
double modis[]={4.31, 3.83, 3.13, 3.51};
double pg3[]={2.5, 3.94, 3.63, 2.08};
double prel[]={2.50, 4.39, 4.09, 2.95};
double nexl[]={3.4,3.8,3.3,2.7};
double
reg(pixel, parameter, *modis, *pg3, *prel, *nexl);
system(«pause»);
return 0;
}

Понравилась статья? Поделить с друзьями:
  • Error initialize scatter file failed
  • Error initialize libfreshclam init failed
  • Error initialization video mode 640x480 fallout 2
  • Error init webgl failed
  • Error init render что это