1

I can't figure out how to set default value for integer in structure. For example

 typedef struct {
        char breed[40];
        char coatColor[40];
        int maxAge = 20;
    } Cat;

The code above gives me an error on execution - Expected ';' at end of declaration list

jingo
  • 1,064
  • 5
  • 14
  • 22
  • 1
    possible duplicate of [Default values in a C Struct](http://stackoverflow.com/questions/749180/default-values-in-a-c-struct) – Joe Sep 27 '11 at 13:21

5 Answers5

8

You cannot specify default values in C. What you probably want is an 'init' style function which users of your struct should call first:

struct Cat c;
Cat_init(&c);

// etc.
Mike Weller
  • 44,996
  • 15
  • 130
  • 150
7

In C you cannot give default values in a structure. This syntax just doesn't exist.

rodrigo
  • 86,825
  • 11
  • 134
  • 175
2

Succinctly, you can't. It simply isn't a feature of C.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
0

A structure is a type. Types (all types) do not have default values.

// THIS DOES NOT WORK
typedef char = 'R' chardefault;
chardefault ch; // ch contains 'R'?

You can assign values to objects in initialization

char ch = 'R'; // OK
struct whatever obj = {0}; // assign `0` (of the correct type) to all members of struct whatever, recursively if needed
pmg
  • 103,426
  • 11
  • 122
  • 196
0

you can initialize but it's not practical with strings ( better to use your custom functions)

typedef struct {
        char breed[40];
        char coatColor[40];
        int maxAge; 
} Cat;

Cat c = {"here39characters40404040404044040404040",
         "here39characters40404040404044040404040",
          19
};
christophetd
  • 3,774
  • 18
  • 33
cap10ibrahim
  • 587
  • 1
  • 5
  • 16