Serguei Fedorov
Serguei Fedorov

Reputation: 7913

Considering the "Data Type" of a function in C?

I am going to be pretty vague about this and I am sorry. This is homework assignment I am trying to learn something so don't really want the answer but rather an explanation. The question is

  What is the datatype of thisThing

This is not the actual code but a similar example

  int* (*thisThing[])(int*, int*) = {someFunction1, someFunction2}

From what I understand the "datatype" of thisThing is simply an int. However I have never seen a function return type being called a "data type". Is there a reason for this? I know that have pointers to functions in C; are those pointers no different from variable pointers? Any explanation is well appreciated!

Upvotes: 2

Views: 102

Answers (4)

ecatmur
ecatmur

Reputation: 157314

"Datatype" is not a term used in the C standard; the correct term is "type".

In your case, given a value declared as int* (*thisThing[])(int*, int*) you can see that it can be called as: int *result = (*thisThing[0])((int *)0, (int *)0), so the name of its type is unspecified-length array of pointer to function taking (pointer-to-int, pointer-to-int) and returning pointer-to-int.

Pointers to functions are similar to but different from pointers to data; importantly, they are not interchangeable and e.g. you cannot cast a function pointer to void * (whereas you can do that with any data pointer). This is to ensure that your program runs on a platform where function pointers and data pointers have different representations.

Upvotes: 0

lvella
lvella

Reputation: 13413

Variable a is an int:

int a;

Variable b in an array of int:

int b[] = {3, 4};

Variable c is a pointer to int:

int *c = &a;

You can also compose types, for instance, d is an array of pointers to int:

int *d[] = {c, b}

Variable e is a pointer to a function returning int and taking a pointer to int as single parameter:

int (*e)(int*);

Thus, what is the type of thisThing ? Clearly is is not simply int...

int* (*thisThing[])(int*, int*) = {someFunction1, someFunction2}

Upvotes: 0

Tanmoy Bandyopadhyay
Tanmoy Bandyopadhyay

Reputation: 985

thisThing is an array of pointer to a (function taking two pointer to integers as arguments and returning a pointer to integer). You may pl.read the chapter of complicated declarations from "K&R" C book.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182619

the "datatype" of thisThing is simply an int

It's actually an array of function pointers where the pointed-to functions are:

int *fun(int *, int *);

You should look into the spiral rule.

Upvotes: 3

Related Questions