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

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

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

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

    返回值放中间:
    int * test()
    jedyu
        2
    jedyu  
       2013-09-26 08:51:35 +08:00
    int *p = NULL;

    int* test();
    iLluSioN
        3
    iLluSioN  
       2013-09-26 08:53:00 +08:00
    为了避免类似的纠结,常年放中间。。。
    GordianZ
        4
    GordianZ  
    MOD
       2013-09-26 08:57:12 +08:00
    放右边,好区别下面两种:
    int *p1, *p2, *p3;
    int* p1, p2, p3
    ivanlw
        5
    ivanlw  
    OP
       2013-09-26 09:00:54 +08:00
    @GordianZ 这样子好理由!如果是函数返回值你怎么处理呢?
    yujnln
        6
    yujnln  
       2013-09-26 09:01:03 +08:00   ❤️ 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-09-26 09:03:14 +08:00
    这个没有定论放在哪边好, 大牛们也是各有各的写法,但我倾向说放左边,这样从语音上比较合理
    int* p;一个指向int型的指针p,放在右边像是在取值。
    xdeng
        8
    xdeng  
       2013-09-26 09:04:18 +08:00
    我有变量名的 习惯放右边 没得放左边
    sinxccc
        9
    sinxccc  
       2013-09-26 09:10:49 +08:00
    放中间或者放右边,放左边太容易歧义了,星号不是用来修饰类型,而是用来修饰变量的。
    jiangtao92
        10
    jiangtao92  
       2013-09-26 10:07:39 +08:00
    其实放在左边也是会出现歧义,以为int* 是一个类型,例如 int* a,b;
    a 是指针,b 还是int。。
    julyclyde
        11
    julyclyde  
       2013-09-26 13:15:46 +08:00
    从语法上应该是
    int *p, i;
    声明一个p指针和i变量

    从语义上讲,p指向一个int,所以int修饰的是*p
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1077 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:17 · PVG 02:17 · LAX 11:17 · JFK 14:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.