-3

How to write this kind of code in C ??

public static Encoding GetEncoding (
    int codepage
)
Matt
  • 14,906
  • 27
  • 99
  • 149
yohan.jayarathna
  • 3,423
  • 13
  • 56
  • 74
  • 2
    You can't have objects in C but you can have pointers to data `struct`ures and everything is public. BTW everything is effectively `static` Are you thinking about C++? Are you trying to use JNI? – Peter Lawrey May 07 '12 at 06:33

3 Answers3

1

There is no public in C. Functions have external linkage by default unless you mark them static explicitly. It's a good idea to have a prototype visible for your function (probably in a header file) when using it, so as to avoid mismatched expectations between the caller and reality :-)

For example, the following would be valid C:

encoding.h:
    typedef void * Encoding;
    Encoding getEncoding (int);

encoding.c:
    #include "encoding.h"
    Encoding getEncoding (int codePage) {
        return 0;
    }

If your intent is to convert C++ (or other OO languages) code to C, there are ways to do it such as here, but it's not for the faint of heart :-) Especially if you're supporting the proper OO concepts like inheritance and polymorphism.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • True, but the closest thing in C to Java's "public" keyword is declaring the function in a header file. – Yusuf X May 07 '12 at 06:37
1

There are no formal methods in C, and the static modifier means something else. There are also no access control modifiers. So:

Encoding *GetEncoding (int codepage) {

}   

In java, the return value would probably be an object reference, so in C you would use a *pointer.

CodeClown42
  • 11,194
  • 1
  • 32
  • 67
0

In C, there is no access control and no this. So public and static are already the only way to do things.

You probably want the header (interface) file to contain the prototype

extern Encoding *GetEncoding ( int codepage );

and the source (implementation) file should have

Encoding *GetEncoding ( int codepage ) {
    return & masterEncodingList[ codepage ]; /* example implementation */
}

The header file might also define Encoding:

struct Encoding {
    const char *name;
    /* other fields */
};

and the source file might define the encodings

Encoding masterEncodingList[] = {
    { "Swahili", /* other fields */ },
    { "Portuguese", /* ... */ },
    /* ... */
};

Have, ah, fun!

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421