+ 2

How to call a function in another function for C++?

Hello everyone, I'm trying to call a function from another but I don't think i'm doing it correctly. Here is my code: int numOfNodes(struct listNode * firstNode){ int countNodes = 0; while(firstNode -> next != NULL){ countNodes ++; } return countNodes + 1; } int middleOfList(struct listNode * firstNode){ int count = 0; ** while(count != numOfNodes(struct listNode * firstNode) / 2) { ** if (count = (numOfNodes(struct listNode * firstNode)/2) - 1){ int previous = firstNode -> num; firstNode -> next; count++; } else{ firstNode -> next; count++; } } ** if(numOfNodes(struct listNode * firstNode) % 2 != 0) { return firstNode -> next -> num; } else { int total = ((firstNode -> next -> num) + previous) / 2 ; return total; } } I'm trying to call numOfNodes in middleOfList but keep getting the error: "error: expected primary-expression before 'struct'" The error occurs where you see ** in my middleOfList function. All answers are appreciated and thank you in advanced.

4th Jan 2020, 12:49 AM
Leo Hunter
Leo Hunter - avatar
2 odpowiedzi
+ 4
Try to call `numOfNodes` like this numOfNodes(firstNode) As I understand it, argument type is not needed on call, only the argument is (cmiiw).
4th Jan 2020, 1:15 AM
Ipang
+ 1
Lpang is correct, you are declaring the functions signature instead of calling it. Additionally as a side note, you do not need the struct keyword in the function signature. In C it is required but in C++ you dont have to do this. In C: struct Thing{}; Is created and used in functions like: struct Thing t; But this is cumbersome so you can do this: typedef struct {} Thing; Use: Thing t; In C++: struct Thing{}; is equivalent to the typdef version in C, so you can just refer to the type as the name of the struct. This is more C++ like
6th Jan 2020, 1:07 AM
Phill