0

Im making a library for a raspberry pi program and im running into trouble of a struct variable having an initial value.

myLib.h

typedef struct {
 int startingNumber = 0;     // this throw an error in C
} myStruct

void increment(myStruct * a){ if(IsNotInitialised(a->startingNumber)) // i dont know ho to checked printf("starting number is not initialised"); else a->startingNumber++ }

It is important that the number must be set by the user of library and incase the user forgets to set the value in the main, i would like for the library to throw an error. I have read that if the value of a property of a struct is not set it will default to 0, but thats seems to be not true. what makes it even worse is everytime i run the program the value seems to be randomly set.

so when the user programs inside the main

main.c

#include <myLib.h>

int main(){ myStruct count; increment(&count); // this must print the error since count.a is not set }

DrakeJest
  • 75
  • 1
  • 10

1 Answers1

2
typedef struct
{
   int startingNumber;
} myStruct;

The typedef declares a new type. It does not declare any instances of that type.

myStruct count;

declares an object of that type.

myStruct count = {23};

declares an object of that type and gives an initial value.

joan
  • 71,024
  • 5
  • 73
  • 106
  • I need to throw an error when the user FORGETS to give an initial value (just like in my main.c example) after declaring the instance of the struct. my library has to be able to know that the user forgot to give the initial value. how would i go about that? – DrakeJest Apr 01 '21 at 20:43
  • @DrakeJest Not sure you can esp if zero is a valid value. See AnT answer in https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value I would look to using a char or string and set it to a known value in your init. routine and check for null or int and check for none zero. There is also the cruel part of me that says the programmer should make sure init. code is called else expect problems (horse / water comes to mind here). –  Apr 01 '21 at 21:45
  • @Andrew in my situation 0 actually is not a valid value. The problem is, 0 is NOT the default value. The value keeps changing. For example i have a uint16_t property of a struct, and without initializing the value and i try printing it, it would result to random numbers like 46837 on one specific runtime, and 46840 on another. And yes this is the exact problem im facing since inside the init() of my library it cant know if the value is declared or not since the default keeps changing – DrakeJest Apr 01 '21 at 21:59
  • @DrakeJest There is a note in the thread If global or static, they will be zeroed. but the whole thread is a bit of a mess. Wonder if the string or char default is standard? –  Apr 01 '21 at 22:44