我想定义一个非常量全局值,在函数中修改它并在其他函数中将其用作常量。
我并不是特别想将它作为参数传递,我已经这样做了。
这是我写的一个也作为参数传递的全局值的示例。 我不喜欢它,因为我可以在主作用域中定义它并将其作为常量参数传递。
#include<stdio.h>
#include <stdlib.h>
int value[2]={0};
void myfun(const int* const value){
printf("%d \n", value[1]);
}
int main(){
value[1] = 1;
myfun(value);
return 0;
}
不过这是一个中间步骤。我希望让该值全局化,并在 myfun 中仅将其用作常量,而不将其作为参数传递。有什么指令可以帮助它吗?
我无法复制整个数组。相当大(GB 量级)。
这既是为了调试目的(常数需要是常数),也是为了性能。
您的要求相互矛盾:
我想定义一个非常量全局值,在函数中修改它并在其他函数中将其用作常量。
如果它必须是“全局的”,那么这本身就意味着每个人都可以访问它。您可以通过多种方式限制访问,通过声明
static
或使用具有不完整结构类型的设计。然而,这确实涉及传递一个指向变量的指针,但您也不希望这样做。所以现在可以了。
如果不考虑重入问题,一个明智的妥协可能是将其声明为函数内的本地
static
:
const int* do_stuff_with_x (const int* something)
{
static int x [2];
if(something != NULL)
{
x[0] = *something; // writes to the variable only happen here
}
else
{} // the function was called just for the purpose of obtaining access to the variable
return x; // this is OK since the variable has static storage duration
}
使用示例:
int something = 123;
// update and read the variable both at once:
const int* ptr = do_stuff_with_x(&something);
// only update the variable:
(void) do_stuff_with_x(&something);
// only read the variable:
const int* ptr = do_stuff_with_x(NULL);
我认为最简单的选择是仅在外部公开指向数组内容的指针:
#include <stdio.h>
const int * const value;
void myfun(){
printf("%d \n", value[1]);
}
/*
* The static and dynamic initialization below can be in a compilation unit
* isolated from the compilation units where the read-only value is required.
*/
static int value_priv[2] = {0};
const int * const value = value_priv;
int main(){
value_priv[1] = 1;
myfun();
return 0;
}
当然,被赋予只读访问权限的代码可以通过执行一些类型转换恶作剧来获得对数组内容的写访问权限。如果这是一个问题,则只能通过函数调用来访问数组内容,但这会产生需要额外函数调用的开销。