#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2005
    Posts
    21
    Rep Power
    0

    Declaring function in structure in C


    Can we in any case declare functions in C structure.
    Code:
    #include <stdio.h>
    #include <conio.h>
    
    struct temp
    {
      int a;
      void get_data()
      {
        printf("Enter value of a : ");
        scanf("%d",&a);
      }
    }T;
    
    int main()
    {
       T.get_data();
    }
    This works fine in C++ i.e test.cpp (g++ compiler) , but fails in C i.e test.c(gcc compiler) showing error:

    8:field `get_data' declared as a function
    8:[Warning] no semicolon at end of struct or union
  2. #2
  3. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Well that is the fundamental difference between C and C++. C++ supports classes (and in C++ a struct is a special case of a class), and C does not.

    In C you would implement the class as a structure with functions that take a 'this' pointer explicitly, which is essentially what C++ does under the hood. Coupled with a sensible naming convention so you know what functions belong to which classes (again something C++ does under then hood with name-mangling), you get close to object-based if not object-oriented programming.

    Example:

    Code:
    typedef struct temp
    {
        int a;
    
    } classTemp ;
    
    void classTemp_GetData( classTemp* pThis )
    {
        printf( "Enter value of a : " );
        scanf( "%d", &(pThis->a) );
    }
    
    classTemp T ;
    
    int main()
    {
       classTemp_GetData( &T );
    }
    However, as you can see without language support for classes, implementing then can become tiresome. It all rather begs the question that if you can do it in C++ why would you use C at all!?

    Clifford

    Comments on this post

    • sizablegrin agrees
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    You can also accomplish the functionality you are looking for with function pointers. For example:
    Code:
    #include <stdio.h>
    
    struct t {
            int a;
            void (*fun) (int * a);
    } ;
    
    void get_a (int * a) {
            printf (" input : ");
            scanf ("%d", a);
    }
    
    int main () {
            struct t test;
            test.a = 0;
    
            printf ("a (before): %d\n", test.a);
            test.fun = get_a;
            test.fun(&test.a);
            printf ("a (after ): %d\n", test.a);
    
            return 0;
    }
    Which results in the following:
    Originally Posted by output
    $ ./a.out
    a (before): 0
    input : 42
    a (after ): 42
    However, what clifford said still holds. You will need to pass the address of the internal element around to the function and if you are gonna do that why embed the function call within the struct anyway.
    No use reinventing the wheel; if you can use C++ do so.

    Comments on this post

    • sizablegrin agrees
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog
  6. #4
  7. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,806
    Rep Power
    1570
    Conversely, if your goal is to learn C, or you need to use C for some purpose that C++ won't work for, then you need to learn the idioms of C rather than trying to force-fit C++ techniques into it.

    In C, the functions and data structures are more or less bare; the language gives a minimum of support for combining data structures together, and none at all (directly) for including functions with those data structures. The purpose of C is to have a language that translates as directly as possible into machine code, more like a portable assembly language than a higher-level language such as C++ (not that C++ is all that high-level). C let's you get very close to the machine, getting into details that most languages abstract away; the down side of this is that you have to get close to the machine in C to use the language to its utmost. It takes a completely different approach to programming from C++, something that the surface similarities between them hide.

    Comments on this post

    • sizablegrin disagrees : C is not cheap assembly language.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  8. #5
  9. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by Schol-R-LEA
    [...] or you need to use C for some purpose that C++ won't work for
    Being essentially a superset of C I cannot think of any such purpose. And before any one flames in response to that, those areas where C++ is not an exact superset do not affect its sutability for any particular application compared to C - in most cases it makes it more suited. There are some platforms for which there is no C++ compiler, or at least no complete implementation, but that would be the only reason, such platforms usually have restricted implementations of C too because of architectural and resource constraints.
  10. #6
  11. Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jun 2005
    Posts
    5,964
    Rep Power
    4852
    I agree wholeheartedly with Clifford. The structure issue points out one area where C++ is not a mere superset. Despite that, I can think of very few good reasons to use C over C++, except absolute fiat.
    Write no code whose complexity leaves you wondering what the hell you did.
    Politically Incorrect DaWei on Pointers Grumpy on Exceptions
  12. #7
  13. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,806
    Rep Power
    1570
    Originally Posted by Clifford
    Originally Posted by Schol-R-LEA
    [...] or you need to use C for some purpose that C++ won't work for
    Being essentially a superset of C I cannot think of any such purpose.
    I think I misspoke myself here: I wasn't thinking in terms of something that couldn't be done in C++, but something which the OP was required to use C for - a class on the specific language, or a job where the tools are chosen by management fiat, as SizeableGrin put it. You're correct in that C++ can be used for pretty much anything C can be.

    As for C not being a 'cheap assembly language"... well, I suppose it depends on just what you mean by 'cheap', but yes, I'll admit that calling it a portable assembly language isn't accurate (and is a bit of a clich&eacute; in any case), but I wanted to emphasize the fact that C focuses more on efficiency and flexibility over abstraction.

    I apologize if anything I said was misleading or mistaken.
    Last edited by Schol-R-LEA; July 22nd, 2008 at 07:45 PM.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  14. #8
  15. Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jun 2005
    Posts
    5,964
    Rep Power
    4852
    You're one of the very best contibutors I know, Schol, but C is most definitely not assembly language. Neither is it C++ or Python or Haskell or Lisp.

    It's very intermediate, a language that succeeded in divorcing, to some extent, the programmer from the architecture. It allowed a degree of abstraction when resources were not copious or cheap, and still could cost more than a programmer's time. Aside from pure habit, it's day is mostly gone.

    Strictly personal opinion, of course.
    Write no code whose complexity leaves you wondering what the hell you did.
    Politically Incorrect DaWei on Pointers Grumpy on Exceptions
  16. #9
  17. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    p-code, Java byte code, and CLR byte code are more analogous to portable machine code (although not assembler, I don't think anyone actually programs directly in these). Machine languages do not have the high level constructs of C, except as provided as macros and pseudo-ops by some assemblers, but fundamentally assembler language is characterised by one assembler instruction resolving to exactly one machine instruction, the abstraction being merely one of providing meaningful (if rather terse) names (or mnemonics) to machine instruction codes. That characterisation does not apply to C.

    Given that in Stroustrup's words; "In C++ it's harder to shoot yourself in the foot, but when you do, you blow off your whole leg.", there are often valid reasons for not using C++, mostly to do with staff experience and expertise, and sometimes to do with a healthy cautious conservatism (especially prevalent in embedded systems development). In the longer term however, it is generally better to invest in good staff or good staff training/mentoring, and also a good static analysis tool, and then reap the benefits of C++.

    Clifford
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    11
    Rep Power
    0
    You can not define a function in a C structure. But you can have a pointer to a function (as a variable) in C.
    There isn't much of a difference between C and C++ in terms of defining functions inside either structures of classes. It's just the way they are implemented that differs. In that, a function inside a C++ struct / class is same as a pointer to the function with first parameter being 'this'.
  20. #11
  21. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by sahuarito
    [...] a function inside a C++ struct / class is same as a pointer to the function with first parameter being 'this'.
    Not quite; there is an extra level of indirection on your C suggested implementation, and the function pointer increases the structure size whereas a member function has no effect on the size of a class object.
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    11
    Rep Power
    0
    Originally Posted by clifford
    Not quite; there is an extra level of indirection on your C suggested implementation, and the function pointer increases the structure size whereas a member function has no effect on the size of a class object.
    Obviously, since you're adding an extra variable inside a C structure. In C++, it's taken care by the compiler, in that a C++ struct/class you are not adding a variable.
  24. #13
  25. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by sahuarito
    Obviously, [...]
    It is not that obvious perhaps to someone who may have believed you when you said it was "the same". Sometimes the difference matters. Yes the compiler deals with it, but it does not deal with it through indirection, so it is not the same.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    C's day isn't over yet


    Originally Posted by sizablegrin
    You're one of the very best contibutors I know, Schol, but C is most definitely not assembly language. Neither is it C++ or Python or Haskell or Lisp.

    It's very intermediate, a language that succeeded in divorcing, to some extent, the programmer from the architecture. It allowed a degree of abstraction when resources were not copious or cheap, and still could cost more than a programmer's time. Aside from pure habit, it's day is mostly gone.

    Strictly personal opinion, of course.
    I'm thinking not many people in this forum have worked with embedded design? C++ is not an option for microcontrollers or FPGA, and assembly would limit the engineer/code to limited architectures. C allows better portability while still being being easily compiled into assembly. C hasn't finished yet, and to be honest as an embedded design engineer I look at it from the other direction of not seeing why C++ is necessary. If I have resources to burn and can use classes, I use C#, if not, I use C. C++ is just the piggy in the middle to me.
  28. #15
  29. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,117
    Rep Power
    1803
    Originally Posted by Stiege
    I'm thinking not many people in this forum have worked with embedded design? C++ is not an option for microcontrollers or FPGA, and assembly would limit the engineer/code to limited architectures. C allows better portability while still being being easily compiled into assembly. C hasn't finished yet, and to be honest as an embedded design engineer I look at it from the other direction of not seeing why C++ is necessary. If I have resources to burn and can use classes, I use C#, if not, I use C. C++ is just the piggy in the middle to me.
    First of all, was there any reason to resurrect a 5 year old thread to make a point largely irrelevant to the thread in question? No one suggested that C was "dead" and the discussion is not about embedded systems either.

    I am in fact an embedded systems professional of 24 years standing and can assure you that C++ is quite definitely an option for microcontrollers and softcore processors on FPGA (Neither ISO C nor ISO C++ are HDLs suitable for direct FPGA coding, though Handel C and SystemC are languages adapted for that purpose).

    Currently when recruiting embedded systems engineers, I specifically look for C++ and make a point of discussing its merits or otherwise in interviews, candidates generally fall into three categories regarding C++:
    1. Ill-informed luddite.
    2. Cautious pragmatist aware of the benefits and how to avoid the potential pitfalls.
    3. Gung-ho C++ fanboys advocating the use of STL, Boost and C++x11 everywhere.


    I recruit the middle category.

    Some reading on the subject:


    And for balance (though most of the above are in fact already balanced views):


    As for the suggestion that you might use C# in embedded systems, well for a very small subset of systems that are not hard real-time and run a Microsoft platform such as .NET Micro, WinCE or Windows Embedded you can. I would guess that is less than one percent of embedded applications.

    I have used C++ it on ARM microcontrollers (ARM7, ARM9 and Cortex-M) for the last 12 years or so, and even on Atmel AVR. It has contributed to better systems with greater code reuse and maintainability. The last time I had to use C on an embedded system was on a dsPIC because for some bizarre reason Microchip decided to exclude C++ compilation from their GNU gcc based compiler; this should be a developer choice, nit a chip-vendor decision (other vendors do support C++ on dsPIC/PIC24). Lower end PICs are indeed less to suited to C++, but there again they are not particularly well suited to C either.
    Last edited by clifford; February 9th, 2013 at 10:45 AM.

IMN logo majestic logo threadwatch logo seochat tools logo