V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ivanlw
V2EX  ›  问与答

C++指针的星号应该放哪边?int* p还是int *p呢……头痛好多年了……还有int* test();还是int *test();

  •  
  •   ivanlw · 2013 年 9 月 26 日 · 6428 次点击
    这是一个创建于 4497 天前的主题,其中的信息可能已经有所发展或是发生改变。
    11 条回复    1970-01-01 08:00:00 +08:00
    timonwong
        1
    timonwong  
       2013 年 9 月 26 日   ❤️ 1
    我的习惯

    变量声明放右边:
    int *p1, *p2, *p3;

    返回值放中间:
    int * test()
    jedyu
        2
    jedyu  
       2013 年 9 月 26 日
    int *p = NULL;

    int* test();
    iLluSioN
        3
    iLluSioN  
       2013 年 9 月 26 日
    为了避免类似的纠结,常年放中间。。。
    GordianZ
        4
    GordianZ  
       2013 年 9 月 26 日
    放右边,好区别下面两种:
    int *p1, *p2, *p3;
    int* p1, p2, p3
    ivanlw
        5
    ivanlw  
    OP
       2013 年 9 月 26 日
    @GordianZ 这样子好理由!如果是函数返回值你怎么处理呢?
    yujnln
        6
    yujnln  
       2013 年 9 月 26 日   ❤️ 2
    1. int* p; // legal but might be misleading

    We say that this definition might be misleading because it suggests that int* is the
    type of each variable declared in that statement. Despite appearances, the base type
    of this declaration is int, not int*. The * modifies the type of p.

    2. int* test(); // func returns a pointer to int
    angelface
        7
    angelface  
       2013 年 9 月 26 日
    这个没有定论放在哪边好, 大牛们也是各有各的写法,但我倾向说放左边,这样从语音上比较合理
    int* p;一个指向int型的指针p,放在右边像是在取值。
    xdeng
        8
    xdeng  
       2013 年 9 月 26 日
    我有变量名的 习惯放右边 没得放左边
    sinxccc
        9
    sinxccc  
       2013 年 9 月 26 日
    放中间或者放右边,放左边太容易歧义了,星号不是用来修饰类型,而是用来修饰变量的。
    jiangtao92
        10
    jiangtao92  
       2013 年 9 月 26 日
    其实放在左边也是会出现歧义,以为int* 是一个类型,例如 int* a,b;
    a 是指针,b 还是int。。
    julyclyde
        11
    julyclyde  
       2013 年 9 月 26 日
    从语法上应该是
    int *p, i;
    声明一个p指针和i变量

    从语义上讲,p指向一个int,所以int修饰的是*p
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   853 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:27 · PVG 05:27 · LAX 13:27 · JFK 16:27
    ♥ Do have faith in what you're doing.