【问题标题】:Line of code within curly braces花括号内的代码行
【发布时间】:2016-12-09 20:20:53
【问题描述】:

我最近在一个方法中遇到了一行如下:

range_t range = {0, bytes_usage(value), hm->pair_size};

那么,在代码的 sn-p 周围加上花括号是什么意思?

【问题讨论】:

  • 它是一个初始化器,即设置比简单值类型更复杂的值,例如 int。 range_t 可能是一个结构
  • @pm100 哦,好吧!有没有其他的写法?
  • 尝试阅读手册,寻找“初始化结构”
  • 请记住,在这里说“谢谢”的首选方式是对好的问题和有用的答案进行投票,并接受对您提出的任何问题最有帮助的答案(这也给您一个小幅提升您的声誉)。请查看About 页面以及How do I ask questions here?What do I do when someone answers my question?

标签: c


【解决方案1】:

您使用的结构是未定义的,但显然有至少三个成员,它们在大括号(大括号)内初始化。

range_t range = {0, bytes_usage(12), hm->pair_size};

第一个是硬编码的0。第二个是函数调用的结果。第三个是另一个struct的成员的值,需要一个struct指针。

#include <stdio.h>

typedef struct {                // a struct with 3 members
    int a, b, c;
} range_t;

typedef struct {                // a struct that will be used to initialise another
    int pair_size;
} hm_type;

int bytes_usage(int v)          // a function that returns a value
{   
    return v + 1;
}

int main(void) {
    hm_type hh = {42};          // a struct with data we need
    hm_type *hm = &hh;          // pointer to that struct (to satisfy your question)
    range_t range = {0, bytes_usage(12), hm->pair_size};    // your question
    printf("%d %d %d\n", range.a, range.b, range.c);        // then print them
}

程序输出:

0 13 42

【讨论】:

  • typedef int range_t[3];?
【解决方案2】:

这是一个初始化器。它正在初始化range,这是range_t 的一种类型,可能是一个结构。有关示例,请参阅此问题:

How to initialize a struct in accordance with C programming language standards

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2015-12-19
    • 1970-01-01
    • 2017-04-07
    • 2016-12-18
    • 2019-11-28
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多