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).

  • 相关阅读:
    HTTP以及TCP协议
    分布式理论
    JAVA基础面试题
    JAVA基础面试题
    vue 中百度富文本初始化内容加载失败(编辑操作某列数据时,富文本中内容偶尔会为空)
    CodeMirror的使用方法
    JSON格式化,JSON.stringify()的用法
    promise与await的用法
    服务器端node.js
    数组扁平化
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/7443350.html
Copyright © 2011-2022 走看看