簡體   English   中英

編寫函數的const和非const變體

[英]Writing a const and non-const variant of a function

我實現了一個相當復雜的函數,但是為了一個最小的例子,讓我們堅持下去:

(const) char * my_function((const) char *input) {
  return input;
}

當我需要使用const調用函數一次並使用非const值調用一次時,會出現問題:

const char *a = "ABC";
char b[3];

// The following fails without using const in the declaration of my_function
const char *result_a = my_function(a);

// The following fails when using const in the declaration of my_function
char *result_b = my_function(b);

可以在普通C中解決這個問題而不用不同名稱重復相同的功能嗎?


我知道這可以用第二個文件或非常長的#define ,但是有一個優雅的解決方案嗎?

如果在函數內,參數指向的字符串沒有被更改,那么函數定義可能看起來像

char * my_function( const char *input ) 
{
    // ...
    return ( char * )input;
}

因此你可以寫

const char *a = "ABC";
char b[3];

const char *result_a = my_function(a);
char *result_b = my_function(b);

也就是說,函數的用戶有責任正確處理返回的對象。

此方法用於大多數標准C字符串函數。

例如

char *strstr(const char *s1, const char *s2);

暫無
暫無

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

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