zoukankan      html  css  js  c++  java
  • Use of ‘const’ in Functions Return Values

    Use of 'Const' in Function Return Values

    为什么要在函数的返回值类型中添加Const?

    1、Features

    Of the possible combinations of pointers and ‘const’, the constant pointer to a variable is useful for storage that can be changed in value but not moved in memory.

    Even more useful is a pointer (constant or otherwise) to a ‘const’ value. This is useful for returning constant strings and arrays from functions which, because they are implemented as pointers, the program could otherwise try to alter and crash. Instead of a difficult to track down crash, the attempt to alter unalterable values will be detected during compilation.

    For example, if a function which returns a fixed ‘Some text’ string is written like

        char *Function1()
        { return “Some text”;}
    

    then the program could crash if it accidentally tried to alter the value doing

        Function1()[1]=’a’;
    

    whereas the compiler would have spotted the error if the original function had been written

        const char *Function1()
        { return "Some text";}
    

    because the compiler would then know that the value was unalterable. (Of course, the compiler could theoretically have worked that out anyway but C is not that clever.)

    2、Examples

    Use of 'const' in Function Return Values

    #include <iostream>
    using namespace std;
    const char * function()
    {
    	return "some Text";
    }
    
    const int function1()
    {
    	return 1;
    }
    
    int  main()
    {
    	
    	char * h = function(); //1 does not compile
    	int h = function1();   //2 works
    
    	return 0;
     }
    
    
    

    function returns a pointer to const char* and you can't just assign it to a pointer to non-const char (without const_cast, anyway). These are incompatible types.
    function1 is different, it returns a constant int. The const keyword is rather useless here - you can't change the returned value anyway. The value is copied (copying doesn't modify the original value) and assigned to h.

    For function to be analogue to function1, you need to write char* const function(), which will compile just fine. It returns a constant pointer (as opposed to a non-const pointer to a const type).

  • 相关阅读:
    9011,9012,9013,9014,8050,8550三极管的区别
    XP制动关机CMD命令
    搭建系统框架发现的三个Web.Config问题
    监听公众号返回按钮,直接退出到公众号页面
    微信公众号h5页面自定义分享
    博客园页面设置
    js 中加减乘除 比较精确的算法,js本身有些运算会出错,这里给出较精确的算法
    HTML属性
    HTML属性
    处理ajax数据;数据渲染(细节)
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/7443350.html
Copyright © 2011-2022 走看看