2

I have an assignment where I have to convert a c++ like program to a c program.

If I have something like

class B {
    int var;
    int somefunction(){
        some code here
    }
}

it would get changed to

struct B{
    int var;
}

int somefunction(){
    some code here
}

Basically, I have to change class to struct every time I see it, and if there is a function I have to move it out outside the struct now.

What is the best approach to doing something like this? I get the theory behind this but not sure how to go about approaching it.

glennsl
  • 28,186
  • 12
  • 57
  • 75
FreeStyle4
  • 272
  • 6
  • 17

1 Answers1

6

Typically you pass a pointer to the struct to the function. For example, if you had this C++ code:

class A {
    private:
       int x;
    public:
       A() : x(0) {
       }
       void incx() {
          x++;
       }
};

the equivalent C code would be:

struct A {
    int x;
};

void init( struct A * a ) {   // replaces constructor
    a->x = 0;
}

void incx( struct A * a ) {
    a->x++;
}

And then call it like this:

struct A a;
init( & a );
incx( & a );

But I have to ask why you think you need to convert C++ code to C?

  • i'm curious to know what's the reason of this conversion :) – Mohsen_Fatemi Jan 17 '17 at 21:54
  • It is an assignment for school. I have to parse a c++ like program and the output should be a c program – FreeStyle4 Jan 17 '17 at 21:54
  • I think I worded my question poorly. It was more asking the best approach on how I would parse such a file. Open the c++ file, read the file line by line, if I see class, change it into struct etc – FreeStyle4 Jan 17 '17 at 21:57
  • 3
    @Free That would be very, very difficult. You would effectively be writing a C++ compiler with C as its target language. Which was what the first C++ compiler (cfront) did, but that was far from a trivial undertaking. I think you may have misunderstood your assignment. –  Jan 17 '17 at 21:58