Use C++ possibilities in C [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
It might be a silly question, but I'm interested in it very much. Is it possible to implement operator new, dynamically expanding arrays, classes in pure C?
Any links or code examples will be appreciated.

new: #define new(type) malloc(sizeof(type)) (have to call it using function syntax, like struct stat *st = new(struct stat))
dynamically expanding arrays: realloc plus some custom array-manipulation functions (like push_back, etc.) - this is commonly implemented by third-party C utility libraries (and, as #Mgetz points out, some compilers have built-in extensions for it)
classes: structs with function pointer members (this is very common in several projects, such as the Linux kernel)
You might want to look at GObject, which is a C library providing some object-oriented features to C. Also see the dozens of hits you get for googling "Object-Oriented C".

A quick google search revealed this:
http://ooc-coding.sourceforge.net/
Haven't read it through but it sounds like what you're after.
Yes, it is possible (common?) to implement object orientedness in C - or at least the bits that are especially needed.
An example is a once created a garbage collector by storing the pointers to malloced memory and the free function in linked lists.
The best thing about C is that it just works and there is almost zero overhead. The more work a language does for you automatically can mean there is a lot more overhead - though this is not always the case.

It depends if it is OK for you to reimplement the compiler.
If it's ok - you can do whatever you wish, otherwise:
new - as an operator - no, but you can define a function + macros that will simulate it.
classes - yep, you can. you may simulate it pretty closely with static functions and an array of pointers to functions. But there will be no overloading.
expanding arrays - yes, with the classes simulation above.

Related

Why functional programming over c [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
How is functional programming useful over normal procedural languages like c or object oriented programming languages like c++ and where does it shine?
C lacks several features of functional programming that need to be worked around (likewise, while you can write in an object-oriented style in C, you need to work around several missing features as well).
C functions are not first-class objects. You cannot return a function from a function, store a function in a variable, or pass a function to another function. You cannot nest functions, and you cannot create anonymous functions. The workaround is that C does allow you to use pointers to functions, so you can write a function that takes a pointer to a function as an argument, but this is not as clean as what you can do in a language oriented towards functional programming.
C lacks closures, which are a way of capturing the “environment” of execution at a particular point in a program (namely, what variable names are bound to).
C lacks generics, except in the most broad sense. In most functional languages, it is possible to write one function which applies to a large number of different types because they don’t depend on specific attributes of those types.
C is a low level language giving the programmer the full control over the program execution. It was newer designed to thigh level abstract language.
Functional programming is not popular and most languages used nowadays are object oriented.
If you need the language which gives you ability to control the program and the environment you should consider C++

Is there a difference between an "object" and a pointer to some kind of struct? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
All of my initial programming experience has been in object-oriented languages (Java, Python). I am now learning C, and it seems that there are still things that resemble objects.
Say for example, a FILE pointer created with the standard C library. This is just a pointer to the memory location of a struct. Is this essentially the same thing as an object in OO languages?
There are existing questions asking about the difference between a struct and a class, but I'm asking about how a program uses those things. A struct is used or accessed via a pointer, while an object is a particular instance of a class. In this sense, it seems that a class is more general than a struct. Though I really only added this paragraph to prevent this questions from being marked as a duplicate, and it strays from my original question.
If a FILE pointer is, indeed, comparable to some FILE object in a different language, then where is the key difference between how that "thing" called FILE will be handled in a object-oriented language vs a non-object-oriented language. Seems like the line starts to blur.
In the C programming language, an object is a “region of data storage in the execution environment, the contents of which can represent values” (cf ISO 9899:2011 §3.15). Almost everything is an object, including pointers, arrays, structures, and integers (but not functions).
This notion however is different from what you understand as an “object” in most object-oriented languages. Notably, objects in C don't have behaviour associated with them, don't have classes and don't have any guarantees whatsoever. There isn't even a guarantee that an object may represent any value at all. An object is only a bit of memory.
The typical API design pattern in procedural programming languages like C is that there is a set of functions (like fopen, fprintf, fclose, fwrite, etc.) and a set of structure types (like FILE) that collect data required for these functions. The association between these structures and the corresponding behaviour is made by passing structures to functions.
You can build all the things you have in an object-oriented language like that, including virtual function calls and classes, you just have to build all of this manually. I believe this is a strength of C as you are not forced into a certain program structure, you can apply the design pattern of object-orientation where appropriate and use other approaches where not.

Recursive coroutines in C (C99) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
While implementing a communication protocol, we have an encoder that traverses some structs recursively and encodes them into a binary message.
So far so good, but now the buffer has to split out into multiple chunks of fixed size, e.g. the upper size of receiving buffer. Since allocating memory for the full message and cutting it consequently seems to be too wasteful (the size of the message is --in theory-- not bounded), the idea is now to implement a coroutine with means of setjmp/longjmp.
At the moment, I have a prototype with two jump buffers - one buffer for resuming the encode function and the second one for simulating the return behavior of the function to jump back to its caller.
Well, it seems to work, but the code looks like coming straight from hell. Are there any 'conventions' for implementing interruptible recursive functions, maybe a set of macros or something? I would like to use only standardized functions, no inline asm in order to stay portable.
Addition:
The prototype is here: https://github.com/open62541/open62541/compare/master...chunking_longjmp
The 'usage' is shown inside of the unit-test.
Currently, coroutine behavior is implemented for a non-recursive function Array_encodeBinary. However, the 'coroutine' behavior should be extended to the general recursive UA_encodeBinary function located here: https://github.com/open62541/open62541/blob/master/src/ua_types_encoding_binary.c#L1029
As pointed out by Olaf the easiest way would be to use an iterative algorithm. However, if for some reason this is difficult, you can always simulate the recursive algorithm with a stack container and a while loop. This at least makes the function easier to interrupt. Pretty good article of how to implement this can be found here. The article is written for c++, but it should not be difficult to convert it to c.

Are function pointers evil? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have been told by more senior, experienced and better-educated programmers than myself that the use of function-pointers in c should be avoided. I have seen the fact that some code contains function pointers as a rationale not to re-use that code, even when the only alternative is complete re-implementation. Upon further discussion I haven't been able to determine why this would be. I am happy to use function pointers where appropriate, and like the interesting and powerful things they allow you to do, but am I throwing caution to the wind by using them?
I see the pros and cons of function pointers as follows:
Pros:
Great opportunity for code modularity
OO-like features in non-OO c (i.e. code and data in the same object)
How else could you reasonably implement a callback?
Cons:
Negative impact to code readability - not always obvious what function is actually called when a function pointer is invoked
Minor performance hit compared to a direct function call
I think Con # 1. can usually reasonably be mitigated by well chosen symbol names and good comments. And Con # 2. will in general not be a big deal. Am I missing something - are there other reasons to avoid function pointers like the plague?
This question looks a little discussion-ey, but I'm looking for good reasons why I shouldn't use function pointers, not opinions
Function pointers are not evil. The main times you "shouldn't" use them are when either:
The use is gratuitous, i.e. not actually needed for what you're doing, or
In situations where you're writing hardened code and the function pointer might be stored at a location you're concerned may be a likely candidate for buffer overflow attacks.
As for when function pointers are needed, Adam's answer provided some good examples. The common theme in all those examples is that the caller needs to be able to provide part of the code that runs from the called function. Without function pointers, the only way you could do this would be to copy-and-paste the implementation of the function and change part of it to call a different function, for every individual usage case. For qsort and bsearch, which can be implemented portably, this would just be a nuisance and hideously ugly. For thread creation, on the other hand, without function pointers you would have to copy and paste part of the system implementation for the particular OS you're running on, and adapt it to call the function you want called. This is obviously unacceptable; your program would then be completely non-portable.
As such, function pointers are absolutely necessary for some tasks, and for other tasks, they are a major convenience which allows general code to be reused. I see no reason why they should not be used in such cases.
No, they're not evil. They're absolute necessary in order to implement various features such as callback functions in C.
Without function pointers, you could not implement:
qsort(3)
bsearch(3)
Window procedures
Threads
Signal handlers
And many more.

Key differences between Ruby and C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What are the key differences between Ruby and C?
They are almost totally different.
Ruby
Strong, dynamic typing
Purely object oriented
Automatic garbage collection and no pointers
Interpreted (or JIT compilation with JRuby/IronRuby)
Reflective
Supports functional programming (closures, coroutines, etc.)
No preprocessor or macros
C
Weak, static typing
Procedural (not object oriented)
Not garbage collected and has pointers
Compiled
No reflection
Does not support functional programming
Has a preprocessor and supports macros
To Ruby From C and C++
Why do you ask? Do you have a specific project or goals in mind?
In addition to what others have already mentioned; I'd also say that some key differences to keep in mind is that the C family is much more portable....or rather, much easier to distribute the finished software. C programs will also be much faster than Ruby...whether that is important or not depends on what you are building (well, that's ALWAYS important, but it isn't a make or break proposition for a lot of programs).
Ruby is just simply a beautiful language to work with (do not underestimate the importance of a language that works with you); developing programs is much quicker in Ruby than C ( C is a compiled language, so that is to be expected )...Ruby is also a pretty simple language to learn; most people consider C to be fairly tough for newbies to pick up.
-- edit --
wow, just saw this was a 3 year old thread....my bad

Resources