在其他函数体中声明函数方法的用例是什么
What is the use case of declaring functions methods within bodies other functions?
我在FreeRTOS中看到了这篇文章来源:
void vApplicationIdleHook( void )
{
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
{
extern void vFullDemoIdleHook( void );
//* Implemented in main_full.c. */
vFullDemoIdleHook();
}
#endif
}
为什么要这样声明函数/方法?优点是什么?我在Java中也看到过类似的代码。
我假设这是项目中唯一使用vFullDemoIdleHook
的地方,所以很明显&简洁,只需在这几行代码中保留声明和函数调用即可。
把声明放在其他地方有什么好处?考虑另一种选择。。。这可能是你更习惯看到的:
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
extern void vFullDemoIdleHook( void );
#endif
void vApplicationIdleHook( void )
{
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
{
//* Implemented in main_full.c. */
vFullDemoIdleHook();
}
#endif
}
我认为这个没有任何优势
我想说,没有理由在函数内部声明函数,因为这会给一种错误的印象,即它在某种程度上仅限于该函数,而事实并非如此。默认情况下,函数具有外部链接(此外,您的代码还专门为函数vFullDemoIdleHook()
指定了extern
),并且声明内部函数应该被认为是一种糟糕的做法(但有效)。
原型应该在头文件中(如果没有头,则在源文件的顶部)。我会把申报单移到main_full.h
:
extern void vFullDemoIdleHook( void ); /* extern keyword is redundant here */
main_full.c:
void vApplicationIdleHook( void )
{
/* The simple blinky demo does not use the idle hook - the full demo does. */
#if( mainCREATE_SIMPLE_BLINKY_DEMO_ONLY == 0 )
{
//* Implemented in main_full.c. */
vFullDemoIdleHook();
}
#endif
}
除非您打算将相同的函数名vFullDemoIdleHook
用于不同的目的(这将非常糟糕),否则不需要有条件地(#if
)声明函数原型。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- 从长整整转换为uint64_t的推荐方法是什么?
- C++:使用方法调用析构函数的顺序是什么?
- 将此布尔值传递给此函数的最有效方法是什么?