开发者

Difference between C and C++

The code given here when compiled by g++ runs fine but gives error on compiling with gcc. Obviously, this is correct for C++ but not for C. Please help me to correct the syntax for C.

# include <stdio.h>
typedef struct demo
{
    int arr[20], i;
    void setvalue(int num)
    {for(i=0;i<20;i++)arr[i]=num;}

    void printvalue()
    {for(i=0;i<20;i++)printf("%d ",arr[i]);}
} example;

int main()
{
    example e;开发者_StackOverflow中文版
    e.setvalue(100);
    e.printvalue();
    return 0;
}

Error log:

stov.c:7:2: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘{’ token
stov.c: In function ‘main’:
stov.c:18:3: error: ‘example’ has no member named ‘setvalue’
stov.c:19:3: error: ‘example’ has no member named ‘printvalue’


You can't have methods in C (that function in the struct). There's more than one way to solve this, but I would simply pass the object as the first argument to the function:

void setvalue(struct demo *d, int num)
{
    int i;
    for(i = 0; i < 20; i++)
        d->arr[i] = num;
}


/* ... */
setvalue(&e, 100);


Here's your problem: Your struct contains methods. That's no good in C.

In C++ a struct is mostly like a class (or rather, a class is mostly like a struct), and can have methods, etc.

In C, this does not apply.


You may use function pointers in struct to emulate OOP.

typedef struct demo
{
  int arr[20], i;
  void (*setvalue)(int num);

  void (*printvalue)();
} example;

then later you can assign a function to the function pointer.

void set_val(int num) {for(i=0;i<20;i++)arr[i]=num;}
example_struct.setvalue = set_val;


I would like to point out that C have function-pointers and function-pointers can be used like C++ member functions, kind of. The clunky syntax can be avoided with some C preprocessor macros and templates (you can use the C preprocessor for generic programming, it's more powerful and versatile then C++ templates, give better type checking and (on modern compilers) faster and smaller code; this programming trick used to be called Code Books by Algol and COBOL programmers (I learned it during a COBOL course in my youth), but have been avoided by C programmers for some stupid reason).

Code not tested, just cobbled it together from the code in the question:

# include <stdio.h>
static void _setvalue(example *obj, int num)
{ int i;
  for(i=0;i<20;i++)
      obj->arr[i]=num;
}

static void _printvalue(example *obj)
{  int i;
   for(i=0;i<20;i++)
       printf("%d ", obj->arr[i]);
}


typedef struct demo
{   int arr[20], i;
    void (*const setvalue)(example *, int) = _setvalue;
    void (*const printvalue)(example *)    = _printvalue;
} example;

int main()
{   example e;
    e.setvalue(&e, 100);
    e.printvalue(&e);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜