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
  • 4
    its an initalizer, ie setting the value of someting more complex that a simple value type , like int. range_t is probably a struct – pm100 Dec 09 '16 at 20:22
  • @pm100 oh okay! Is there an alternate way to write this? – Leah Dec 09 '16 at 20:27
  • try reading a manual, look for 'initializing structs' – pm100 Dec 09 '16 at 20:30
  • Please rememebr that the preferred way of saying 'thanks' around here is by up-voting good questions and helpful answers, and by accepting the most helpful answer to any question you ask (which also gives you a small boost to your reputation). Please see the [About] page and also [How do I ask questions here?](http://stackoverflow.com/help/how-to-ask) and [What do I do when someone answers my question?](http://stackoverflow.com/help/someone-answers) – Jonathan Leffler Dec 10 '16 at 04:35

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
  • 32,572
  • 7
  • 33
  • 51
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
  • 287
  • 6
  • 15