C语言const指针使用技巧之——返回指针的函数

来源:岁月联盟 编辑:猪蛋儿 时间:2012-05-18

引言——
     在c语言中,有些函数回返回指针,即为返回指针的函数。通常情况下函数的实现方不希望函数的调用方修改指针指向的内容。
解决方案——
     在函数返回的时候返回一个指向 const 变量的指针。示例代码如下
 
[cpp]
#include "stdafx.h" 
 
static const int* testPointerToConstVaribles(); 
 
int _tmain(int argc, _TCHAR* argv[]) 

    const int *TestPointer = NULL; 
 
    TestPointer = testPointerToConstVaribles(); 
     
    return 0; 

 
const int* testPointerToConstVaribles() 

    static int ConstVarible = 100; 
 
    return &ConstVarible;//返回指向const变量指针 

如果在编码中试着改变指针指向的值就会出错,以下是出错代码
[cpp]
#include "stdafx.h" 
 
static const int* testPointerToConstVaribles(); 
 
int _tmain(int argc, _TCHAR* argv[]) 

    const int *TestPointer = NULL; 
 
    TestPointer = testPointerToConstVaribles(); 
        *TestPointer = 34;//修改指针指向的值,引起编译错误 
 
    return 0; 

 
const int* testPointerToConstVaribles() 

    static int ConstVarible = 100; 
 
    return &ConstVarible;//返回指向const变量指针 

上面代码在VS 2005 下编译会出现以下错误(错误代码块为 "*TestPointer = 34;//修改指针指向的值,引起编译错误")
" error C3892: 'TestPointer' : you cannot assign to a variable that is const"

总结
通过以上方案可以防止非法修改指针指向的值。

 


摘自 DriverMonkey的专栏

图片内容