Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output of using sizeof on a function [duplicate]

Tags:

c

sizeof

Why does the following code give:

#include<stdio.h>

int voo()
{
    printf ("Some Code");
    return 0;
}


int main() {
    printf ("%zu", sizeof voo);
    return 0;
}

The following output:

1
like image 855
Expert Novice Avatar asked Aug 08 '11 20:08

Expert Novice


People also ask

What is the output of sizeof?

When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.

What does the sizeof operator return?

The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.

What is the use of sizeof () function in C?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.

What is sizeof () operator gives syntax?

The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer.


1 Answers

The C language does not define sizeof for functions. The expression sizeof voo violates a constraint, and requires a diagnostic from any conforming C compiler.

gcc implements pointer arithmetic on function pointers as an extension. To support this, gcc arbitrarily assumes that the size of a function is 1, so that adding, say, 42 to the address of a function will give you an address 42 bytes beyond the function's address.

They did the same thing for void, so sizeof (void) yields 1, and pointer arithmetic on void* is permitted.

Both features are best avoided if you want to write portable code. Use -ansi -pedantic or -std=c99 -pedantic to get warnings for this kind of thing.

like image 168
Keith Thompson Avatar answered Sep 20 '22 22:09

Keith Thompson