Johnyy
Johnyy

Reputation: 2116

Why does my function pointer code run with no errors?

I have this:

typedef void (*funcptr) (void);

int main(){

    funcptr(); //this can compile and run with no error . WHAT DOES IT MEAN? WHY NO ERRORS?


}

Upvotes: 4

Views: 220

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320481

In C++ language, any expression of the form some_type() creates a value of type some_type. The value is value-initialized.

For example, expression int() creates a value-initialized value of type int. Value-initialization for int means zero initialization, meaning that int() evaluates to compile-time integer zero.

The same thing happens in your example. You created a value-initialized value of type funcptr. For pointer types, value-initialization means initialization with null-pointer.

(Note also, that it is absolutely incorrect to say that expressions like int(), double() or the one in your OP with non-class types use "default constructors". Non-class types have no constructors. The concept of initialization for non-class types is defined by the language specification without involving any "constructors".)

In other words, you are not really "playing with function pointer" in your code sample. You are creating a null function pointer value, but you are not doing anything else with it, which is why the code does not exhibit any problems. If you wanted to attempt a call through that function pointer, it would look as follows funcptr()() (note two pairs of ()), and this code would most certainly crash, since that's what usually happens when one attempts a call through a null function pointer value.

Upvotes: 5

kennytm
kennytm

Reputation: 523294

The statement creates a funcptr instance by its default constructor* and discard it.

It is just similar to the code

int main () {
    double();
}

(Note: * Technically it performs default-initialization as not all types have constructors. Those types will return the default value (zero-initialized), e.g. 0. See C++98 §5.2.3/2 and §8.5/5 for what actually happens.)

Upvotes: 14

Alexander Rafferty
Alexander Rafferty

Reputation: 6233

You are defining a datatype, funcptr, which is a function that takes no parameters and returns void. You are then creating an instance of it, but without an identifier, discarding it.

Upvotes: 1

Related Questions