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,084
  • 5
  • 14
  • 23
  • 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
  • 45,401
  • 15
  • 131
  • 151
7

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

rodrigo
  • 94,151
  • 12
  • 143
  • 190
2

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

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
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
  • 106,608
  • 13
  • 126
  • 198
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,834
  • 20
  • 33
cap10ibrahim
  • 587
  • 1
  • 6
  • 16