• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
pitchblack00

Did you know you can define functions like that in C?

12 posts in this topic

This is something second-year students at my alma mater are expected to learn in depth if they hope to actually pass their third semester. The parsing rules for declarations in C are rather simple once you get them down.
 
Note of course that this is all much easier with typedefs and is by far the recommended way for a C programmer to do something like this:
 
typedef int(*IF)(void);

extern IF make_function(void);
 
In C++11 this all gets even easier using the new using syntax as you no longer have to remember where the name goes inside the typedef:
 
using IF = int(*)();

IF make_function();
1

Share this post


Link to post
Share on other sites

Same here. They had us do a lot of absurd declarations no sane person will ever need, just for practice. "Declare a function that returns an array of function pointers and takes a pointer to an array of int". Looking back, I think all they really wanted to see was who would be smart enough to break it down into multiple typedefs and who would be insane enough to do it all in one line.

0

Share this post


Link to post
Share on other sites

That's right, declarations I knew about as well, but this is definition. Anyway certainly not something I'd like to find in my code base, but that goes to my personal zoo of craziest C gibberish.

0

Share this post


Link to post
Share on other sites

I've typedefed function pointers before, but never a function type. What can one do with the type of a function?

1

Share this post


Link to post
Share on other sites

I've typedefed function pointers before, but never a function type. What can one do with the type of a function?

 

 

The are used all the time in C++.  Many of the algorithmic functions take such a function. Functions that sort or search or generate or do something 'if' will all use them.

 

If you search through the C++ standard libraries you will find several hundred functions that take a predicate, binary predicate, unary function, binary function, or similar. 

 

These are just the same as the prototypes above, typedefs for functions of the form bool(*UnaryPredicate)(T), bool(*BinaryPredicate)(T,T), void(*UnaryFunction)(T), void(*BinaryFunction)(T,T) or similar. The typedef looks very similar to the ones in the original post, except they are templates.

 

The benefit is that you can say:  if(function(a,b)) and it just works.  An example is the std::for_each implementation:

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, UnaryFunction function)
{
   while (first!=last) {
      function (*first);
      ++first;
   }
   return fn; // or, since C++11: return move(fn);
}

In C++ just go through the <algorithm> header, you will find a large number of function overloads taking "Predicate" or "Function" signatures. You will find similar overloads in most of the container classes, and in many other locations through the libraries.

 

 

When people talk about using Lambda functions, this is precisely where a Lambda function is used.

0

Share this post


Link to post
Share on other sites


These are just the same as the prototypes above, typedefs for functions of the form bool(*UnaryPredicate)(T), bool(*BinaryPredicate)(T,T), void(*UnaryFunction)(T), void(*BinaryFunction)(T,T) or similar. The typedef looks very similar to the ones in the original post, except they are templates.

Those are function pointer typedefs, not function typedefs.

0

Share this post


Link to post
Share on other sites

 


These are just the same as the prototypes above, typedefs for functions of the form bool(*UnaryPredicate)(T), bool(*BinaryPredicate)(T,T), void(*UnaryFunction)(T), void(*BinaryFunction)(T,T) or similar. The typedef looks very similar to the ones in the original post, except they are templates.

Those are function pointer typedefs, not function typedefs.

 

 

you can make a pointer to a function type at least:

SomeFunctionType *foo;

 

not much sure of other uses.

would be cool if you could be like (in C):

SomeFunctionType Foo { ... }

or:

{

...

    Foo(SomeFunctionType { ... });   // make and pass closure here...

...

}

or something.

 

but, alas...

 

actually, it is sort of possible to do closures in plain C (without compiler extensions, and using plain function pointers), but tends to involve some amount of pain (and some bit of trickery in the background, and some restrictions), making it not really particularly viable as a general-purpose development practice.

Edited by BGB
0

Share this post


Link to post
Share on other sites


would be cool if you could be like (in C):
SomeFunctionType Foo { ... }

 

I think the reason why function types can't be used to define functions is because there would be no way to assign argument names, so they are pretty useless by themselves, you can't return them, you can't assign them, but you can construct other types with it.

0

Share this post


Link to post
Share on other sites

Yeah, it would be cool to be able to do closures in c. When i saw that function typedef (not the function pointer typedef), it almost looked like one could declare a variable of a function type, and assign some value to it. Then I recall variables need a size, and have no answer to that.

 

So in c, other than declaring a variable as a pointer to a function type, there doesn't seem to be much use for a function type (it does look nice though, I like function_type * more than function_type_ptr).

 

edit:

Seems like it can be used to replace a forward declaration too, like this

#include <stdio.h>
typedef int main_func_t(void);
main_func_t test_func;
int main(void) {
    main_func_t * test_func2 = &test_func;
    test_func();
    (*test_func2)();
    return 0;
}
int test_func(void){
    puts("hello");
    return 0;
}
Edited by ultramailman
1

Share this post


Link to post
Share on other sites

 


would be cool if you could be like (in C):
SomeFunctionType Foo { ... }

 

I think the reason why function types can't be used to define functions is because there would be no way to assign argument names, so they are pretty useless by themselves, you can't return them, you can't assign them, but you can construct other types with it.

 

 

they could, potentially, retain their argument names from the original typedef:

typedef int (FooFunc)(int x, int y);

 

FooFunc foo0

    { return(x+y); }

 

but, then again, this is also along the lines of wishing to be able to do something like:

void foo(va_list args...)

    { ... }

 

basically, to not require the usual va_start / va_end or the need to have an argument before the elipses (it doesn't ask "that" much, as on many targets, va_list support essentially needs to be built into the compiler anyways).

 

 

Yeah, it would be cool to be able to do closures in c. When i saw that function typedef (not the function pointer typedef), it almost looked like one could declare a variable of a function type, and assign some value to it. Then I recall variables need a size, and have no answer to that.

 

So in c, other than declaring a variable as a pointer to a function type, there doesn't seem to be much use for a function type (it does look nice though, I like function_type * more than function_type_ptr).

 

yeah.

 

several compilers (GCC, Clang, ...) offer closures as extensions, but nothing is supported in standard C.

 

 

in the time back when I had a (sort-of) working C compiler, it had closures, which were full closures (technically a bit closer to JS syntax though).

the main difference (from those provided by GCC) was that basically they were implemented using allocated memory-objects and involved generating an internal runtime call (and would actually quietly fold off closed-over variables into a heap-allocated structure).

 

(the C compiler sub-project eventually died mostly due to it being fairly slow and very buggy...).

 

 

as-is (in my case), it can sort of be done now (with standard C) using API calls (these calls are specific to my codebase), but requires basically putting the closed-over state into a struct, basically like:

typedef int (*foo_closure)(int, int);

struct closure_state_s { int z; };

int closure_function(struct closure_state_s *env, int x, int y)
    { return(x+y+env->z); }

foo_closure SomeFunctionReturningClosure(int z)
{
    struct closure_state_s *env;
    env=gcalloc(sizeof(struct closure_state_s));
    env->z=z;
    return((foo_closure)dyllWrapClosure(closure_function, env, "(ii)i"));
}

and with some annoying drawbacks:

with this interface, it is necessary to manually free the closures and environments later (though they will be reclaimed by the GC on x86-based targets);

the pool is finite-sized on ARM (with a relatively small number of closure-handles available, *);

there is a certain amount of cost in creating them (involves allocating memory and generating the relevant machine-code for the stub);

as can be noted from the code, it is sort of a hassle;

...

 

*: the ARM version uses a plain-C implementation, which comes at a bit of a cost in terms of performance, and requires essentially procedurally generating a big mass of code which basically read-off the argument list and then invoke a "generic function-dispatch" mechanism (basically, a gigantic procedurally generated "switch()"), making the whole thing a bit bulky and slow. there may also only be a small number of available function-handles available for a given set of argument and return types.

 

the x86 and x86-64 versions are a bit faster though, as they dynamically generate machine-code stubs which more directly marshal the arguments lists.

there are restrictions though on certain targets (Linux x86-64), mostly in that the particularly complex ABI means that some cases are not handled (my stuff generally only supports a subset of the SysV/AMD64 ABI, using "simplified" rules in a lot of edge-cases, which while not generally an issue, mean that some potential argument lists (generally those involving passing/returning structs) may fail potentially violently).

 

generally, argument lists containing primitive types and/or pointers and with fewer than 6 arguments are fairly safe though (this is what is supported by the plain-C version), though the generated-machine-code versions are a bit more capable (pretty much arbitrary argument lists are supported, and there is no specific limit as to the available number of closures).

 

this leaves their main use-case mostly for trying to optimize cross-language API calls (mostly C->script calls), which (as-such) are still fairly expensive (at present, often around 200-500 clock cycles, though mostly due to API issues, and with a lot of "generic C interpreter logic" getting in the way. getting it faster would likely involve making the C<->script interface look and behave a bit more like COM+ or similar, with calls more directly into the compiled script code...).

 

 

or such...

Edited by BGB
0

Share this post


Link to post
Share on other sites

I admit I missed a few. BTW, I am extremely worried this is considered something expected to be learnt at priori. It clearly has little reason to be used in general case and I believe those shall be buried forever. Type declarations in C are so easy some *nix ship with a command to decipher them.


Same here. They had us do a lot of absurd declarations no sane person will ever need, just for practice. "Declare a function that returns an array of function pointers and takes a pointer to an array of int". Looking back, I think all they really wanted to see was who would be smart enough to break it down into multiple typedefs and who would be insane enough to do it all in one line

No matter what they wanted to do. What they did, in reality is that some idiot will do that in the real world. Typical academical bullshit. They promote elitarims and production of indecipherable code: should be considered unacceptable by all means.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0