Tuesday 1 February 2011

Grokking C declarations.

What does it mean when some bit of code declares

int (*foo(char))(double); // ?

Forget all those C-to-English recipes - if you're anything like me, shoehorning your thinking into natural language just confuses things.

Instead, chop off the atomic type specifier (the "int"), and think what the remaining expression would mean:

x = (*foo('x'))(3.1416);

Immediately it's clear that if you call foo with a char argument, you get a pointer, that you can dereference (not really necessary to do explicitly for function pointers), to get a function that you can call with a double argument, that returns an int.

If you really still need to know what foo "is": it's a function taking char, returning a pointer to a function taking double, returning int. Rather wordy, and now you still have to translate the English version into some more fundamental / more abstract prelinguistic mental structure.

Thanks to Lee for pointing this trick out to me a few years ago. I'm sure it's all over the Internet for those with whom the search is strong.

1 comment:

  1. The Most Successful Sites for Crypto, Casino & Poker - Goyang
    Goyang Casino & 바카라사이트 Poker is one of the goyangfc most famous 도레미시디 출장샵 and https://deccasino.com/review/merit-casino/ well known crypto bsjeon gambling sites, founded in 2012. They are popular because of their great

    ReplyDelete