1

I recently came across a line in a method as follows:

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

What exactly does this mean then, to have curly braces surrounding the snippet of code?

Leah
  • 57
  • 1
  • 8

2 Answers2

4

The struct you use is undefined but obviously has at least three members, which are initialised within the braces (curly brackets).

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

The first is hard coded 0. The second is the result of a function call. The third is the value of a member of another struct, which needs a struct pointer.

#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
}

Program output:

0 13 42
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

It's an initializer. It's initializing range, which is a type of range_t, which is probably a struct. See this question for some examples:

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

Community
  • 1
  • 1
Tophandour
  • 297
  • 5
  • 15