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

  • 相关阅读:
    angularjs基础——控制器
    angularjs基础——变量绑定
    mysql 小数处理
    centos无法联网解决方法
    mysql 按 in 顺序排序
    html5 file 自定义文件过滤
    淘宝、天猫装修工具
    MapGis如何实现WebGIS分布式大数据存储的
    CentOS
    PHP与Python哪个做网站产品好?
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/7443350.html
Copyright © 2011-2022 走看看