0

I am new to C and I can't get this thing to compile properly, can you help me?

struct tagNode
{
    int v, f;

    struct tagNode *next;

    struct tagNode( int _v )
    {
        v = _v;
        next = NULL;
    }
};

expected identifier or ‘(’ before ‘int’: struct tagNode( int _v )

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
makc2099
  • 3
  • 1
  • 1
    It doesn't compile as C, because the code is C++. – StoryTeller - Unslander Monica Jun 01 '19 at 08:41
  • 1
    If this is supposed to be C, then you can't put functions inside structure definitions - only declarations. – Tom Karzes Jun 01 '19 at 08:45
  • 1
    @StoryTeller And not even valid C++. Constructors can't have the `struct` or `class` keyword in their declaration. – Some programmer dude Jun 01 '19 at 08:58
  • @makc2099 Please take some time to read [the help pages](http://stackoverflow.com/help), take [the SO tour](http://stackoverflow.com/tour), read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jun 01 '19 at 09:00

1 Answers1

0

expected identifier or ‘(’ before ‘int’: struct tagNode( int _v )

this is because of the unexpected struct when you compile in C++

A valid version of your code in C++ can be:

struct tagNode
{
    int v, f;

    tagNode *next;

    tagNode (int _v)
    {
        v = _v;
        next = NULL;
    }
};

but

  • what about f ?
  • the constructor can also be tagNode(int _v) : v(_v), next(NULL) {}
  • and you have a pointer so I recommend you to look at the rule of three

There is no constructor/methods in C so the equivalent of your code in C can be :

#include <stdlib.h>

struct tagNode
{
  int v, f;
  struct tagNode * next;
};

struct tagNode * alloc(int _v)
{
  struct tagNode * r = malloc(sizeof(struct tagNode));

  r->v = _v;
  r->next = NULL;
  return r;
}
bruno
  • 32,421
  • 7
  • 25
  • 37