簡體   English   中英

function 定義中 function 聲明的目的

[英]Purpose of function declaration within function definition

在 C 中,當然可以聲明和定義函數。 這與來自 C++ 的默認構造函數調用交互,產生最棘手的解析問題。 Say I want to declare a function foo , define a function bar and create an instance t , I might mistakenly write this (having Python or Java in mind):

T foo();

T bar() {
    T t();
}

這不會做我想要的,它將聲明一個 function t沒有 arguments (或者可能是任意多個,因為那里沒有寫void ,不確定)並返回類型T 我會得到一個帶有 T t 的T實例T t; .

為什么甚至允許這種語法? 在 function 中聲明 function 有什么意義? linker 無論如何都必須在鏈接時解決這個問題,然后可以在文件 scope 中聲明 function。 是否有一些我遺漏的邊緣案例?

不是正式的解釋,而只是我將使用函數范圍聲明的用例。

Imagine you have a C header file offering an inline static function, but in specific cases this function should rely on an internal helper function which is not part of the API.

// file utils.h
#ifndef UTILS_H
#define UTILS_H

// many other things...

inline static
int
nice_util(int i,
          int j)
{
  int k=i+2*j;
  if(i>10) // should not happen so often
  {
    void ugly_helper_function(int n); // no one else should be aware of this function
    ugly_helper_function(k);
  }
  return k;
}

#endif // UTILS_H

這個頭文件可能有一個實現文件。

// file utils.c

#include <utils.h>
#include <stdio.h>

// many other things...

void
ugly_helper_function(int n)
{
  printf("%s(%d)\n", __func__, n);
}

使用此頭文件可提供預期的 function 但不是內部的(除非您忽略警告)。

// file prog.c
#include <utils.h>

int
main(void)
{
  // ugly_helper_function(5678); // warning: implicit declaration...
  return nice_util(12, 34);
}

如果無法在函數范圍內聲明內部function,我們將不得不在 header 文件中的全局范圍內聲明它,這樣就可以在沒有任何警告的情況下訪問它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM