zoukankan      html  css  js  c++  java
  • c/c++ const

    1
    2
    3
    4
    5
    6
    7
    8
      /*
    一、指针指向的变量的值不能变,指向可变

    int x = 1;
    int y = 2;

    const int* px = &x;
    int const* px = &x;
       //这两句表达式一样效果

    px = &y;              //正确,允许改变指向
    *px = 3;              //错误,不允许改变指针指向的变量的值
    */



    /*
    二、指针指向的变量的值可以改变,指向不可变
      
    int x = 1;
    int y = 2;

    int* const px = &x;


    px = &y;              //错误,不允许改变指针指向
    *px = 3;              //正确,允许改变指针指向的变量的值
    */



    /*
    三、指针指向的变量的值不可变,指向不可变
      
    int x = 1;
    int y = 2;

    const int* const px = &x;
    int const* const px = &x;

    px = &y;              //错误,不允许改变指针指向
    *px = 3;              //错误,不允许改变指针指向的变量的值
    */


    /*
    四、补充
    1、const在*的左边,则指针指向的变量的值不可变;在*的右边,则指针的指向不可变。
    简记“左定值,右定向”。

    2、以下编译出错(gcc 4.4.5)
    int x = 1;
    (int*) const px = &x;

    int x = 1;
    const (int*) px = &x;

    3、
    在c中,对于const定义的指针,不赋初值编译不报错;
    int* const px;等不会报错;

    但是,在C++中,上面二、三两种情况必须赋初值,一可以不赋初值;
    即int* const px;const int* const px;报错,const int* px;不报错,
    必须初始化指针的指向int* const px = &x;const int* const px;

    强烈建议在初始时说明指针的指向,防止出现野指针。
    */


  • 相关阅读:
    python操作MYSQL时防止SQL注入
    防止SQL注入的一些解决方法
    Gitbook 学习链接
    MySQL_编码utf8_bin和utf8_general_ci的区别
    使用linux脚本shell检查大数据各节点服务是否运行正常
    shell脚本监测elasticsearch集群节点
    Filebeat+Kafka+Logstash+ElasticSearch+Kibana搭建日志收集系统
    python中集合用法大全
    python常用内置函数
    跨模块全局变量的使用问题
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2683081.html
Copyright © 2011-2022 走看看