简体   繁体   English

如果语句检查该怎么办?

[英]What does this if statement check do?

In the following code the programmer puts the name of a function inside an if condition as if to check something before going ahead and registering a callback: 在下面的代码中,程序员将函数的名称放在if条件中,好像在继续和注册回调之前先进行检查:

#if _DEBUG
    if(glDebugMessageCallback) // He checks this function, presumably it returns true if it exists
{
        cout << "Register OpenGL debug callback " << endl;
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
        glDebugMessageCallback(openglCallbackFunction, nullptr); // Calls the function here
        GLuint unusedIds = 0;
        glDebugMessageControl(GL_DONT_CARE,
            GL_DONT_CARE,
            GL_DONT_CARE,
            0,
            &unusedIds,
            true);
    }
    else
        cout << "glDebugMessageCallback not available" << endl;  // So if the if condition evaluated to false, the function doesn't exist.
#endif

My question is why this way of checking if a function exists? 我的问题是为什么以这种方式检查功能是否存在? If a function doesn't exist surely you'll get a compile error telling you that the function doesn't exist, this seems strange to me. 如果确定不存在某个函数,则会出现编译错误,告诉您该函数不存在,这对我来说似乎很奇怪。 I know basically the function address evaluates to bool, and I asked a question before about this and was told that function addresses aren't particularly useful as implicit conversion to bool, and I don't see how. 我基本上知道函数地址的评估结果是bool,我之前问了一个问题,并被告知函数地址作为隐式转换为bool并不是特别有用,我不知道怎么做。

I should mention also that the function inside the if condition is a MACRO define, defined as: 我还应该提到if条件中的函数是一个MACRO定义,定义为:

#define glDebugMessageCallback GLEW_GET_FUN(__glewDebugMessageCallback)

If it being a define macro makes a difference. 如果它是define宏,则将有所作为。

glDebugMessageCallback is either going to be null (0), or the (presumably valid) address of a function that matches the signature required. glDebugMessageCallback要么为null(0),要么为与所需签名匹配的函数的(假定有效)地址。

The if statement will evaluate to true for any non-null value, and false for a null value. 如果任何非null值,if语句的结果为true,而对于null值的结果为false。 (there may be a compiler warning, but the code will work.) (可能会有编译器警告,但是代码可以正常工作。)

So, if glDebugMessageCallback was initialized to null, and never set to a function address, the if statement will evaluate to false. 因此,如果glDebugMessageCallback初始化为null,并且从不设置为函数地址,则if语句的计算结果为false。 If glDebugMessageCallback was set to the address of a function, the code inside the if block will execute, and the function will be called. 如果将glDebugMessageCallback设置为函数的地址,则将执行if块中的代码,并将调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM