Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type is a function name in C? [duplicate]

Tags:

c

function

I always understood that in C, func and &func were equivalent. I assume they should both be of type pointer, which is 8 bytes on my Win64 system. However, I just tried this:

#include <stdio.h>  int func(int x, int y) {     printf("hello\n"); }  int main() {     printf("%d, %d\n", sizeof(&func), sizeof(func));     return 0; } 

And expecting to get the output 8, 8 was surprised to get 8, 1 instead.

Why is this? What type exactly is func? It seems to be of type char or some equivalent.
What is going on here?

I compiled this with gcc -std=c99 if it makes a difference.

like image 287
Baruch Avatar asked Sep 15 '13 20:09

Baruch


People also ask

What is type of a function in C?

There are two types of function in C programming: Standard library functions. User-defined functions.

Can two functions have same name in C?

No. In strict C, you cannot do overloading.

What is function name in C with example?

There are two types of functions in C programming: Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times.

Which option is a valid function name in C?

Function name can start with “_” but it cannot start from “*” or asterisk or “#” because there are certain rules which is to be followed by every programmer. Function name also cannot be started with numbers. In C programming you can start your function name with “_” but you can not use other special symbol………


1 Answers

What type is a function name in C?

A function name or function designator has a function type. When it is used in an expression, except when it is the operand of sizeof or & operator, it is converted from type "function returning type" to type "pointer to a function returning type". (This is specified in C99, 6.3.2.1p4).

Now

sizeof(func)

is not valid C as sizeof is not allowed with an operand of function type. This is specified in the constraints of the sizeof operator:

(C99, 6.5.3.4p1 Constraints) "The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member."

But

sizeof(func)

is allowed in GNU C.

There is a GNU extension in GNU C that allows it and in GNU C sizeof with an operand of function type yields 1:

6.23 Arithmetic on void- and Function-Pointers

[...] sizeof is also allowed on void and on function types, and returns 1.

http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

like image 150
ouah Avatar answered Sep 25 '22 06:09

ouah