开发者

Why does my function pointer code run with no errors?

I have this:

typedef void (*funcptr) (void);

int 开发者_C百科main(){

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


}


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.)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜