Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if "set" in c

Tags:

arrays

c

int

If I allocate a C array like this:

int array[ 5 ];

Then, set only one object:

array[ 0 ] = 7;

How can I check whether all the other keys ( array[1], array[2], …) are storing a value? (In this case, of course, they aren't.)

Is there a function like PHP's isset()?

if ( isset(array[ 1 ]) ) ...
like image 342
pop850 Avatar asked Sep 05 '10 19:09

pop850


3 Answers

There isn't things like this in C. A static array's content is always "set". You could, however, fill in some special value to pretend it is uninitialized, e.g.

// make sure this value isn't really used.
#define UNINITIALIZED 0xcdcdcdcd

int array[5] = {UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED};

array[0] = 7;

if (array[1] != UNINITIALIZED) {
   ...
like image 83
kennytm Avatar answered Nov 06 '22 07:11

kennytm


You can't

There values are all undefined (thus random).

You could explicitly zero out all values to start with so you at least have a good starting point. But using magic numbers to detect if an object has been initialized is considered bad practice (but initializing variables is considered good practice).

int array[ 5 ] = {};

But if you want to explicitly check if they have been explicitly set (without using magic numbers) since creation you need to store that information in another structure.

int array[ 5 ]   = {};  // Init all to 0
int isSet[ 5 ]   = {};  // Init all to 0 (false)

int getVal(int index)          {return array[index];}
int isSet(int index)           {return isSet[index];}
void setVal(int index,int val) {array[index] = val; isSet[index] = 1; }
like image 45
Martin York Avatar answered Nov 06 '22 08:11

Martin York


In C, all the elements will have values (garbage) at the time of allocation. So you cannot really have a function like what you are asking for.

However, you can by default fill it up with some standard values like 0 or INT_MIN using memset() and then write an isset() code.

like image 2
BiGYaN Avatar answered Nov 06 '22 08:11

BiGYaN