c++csyntaxg++

How does this function definition work?


I generated a hash function with gperf couple of days ago. What I saw for the hash function was alien to me. It was something like this (I don't remember the exact syntax) :

unsigned int
hash(str, size)
   register char* str;
   register unsigned int size;
{
   //Definition
}

Now, when I tried to compile with a C++ compiler (g++) it threw errors at me for not having str and size declared. But this compiled on the C compiler (gcc). So, questions:

  1. I thought C++ was a superset of C. If its so, this should compile with a C++ compiler as well right?
  2. How does the C compiler understand the definition? str and size are undeclared when they first appear.
  3. What is the purpose of declaring str and size after function signature but before function body rather than following the normal approach of doing it in either of the two places?
  4. How do I get this function to compile on g++ so I can use it in my C++ code? Or should I try generating C++ code from gperf? Is that possible?

Solution

  • 1.  C++ is not a superset, although this is not standard C either.

    2/3. This is a K&R function declaration. See What are the major differences between ANSI C and K&R C? .

    4. gperf does in fact have an option, -L, to specify the language. You can just use -L C++ to use C++.