Home > Enterprise >  is there is a way to make a variable take only certain values?
is there is a way to make a variable take only certain values?

Time:06-01

Is there any way to define a variable for example that only accepts one values from 1 to 100?

If the user try to assign a value that is out of this interval the program signs an error.

I'm not looking for an algorithm of input control, like this:

#include <stdio.h> 

int main ( ) {
    int n ;
    printf("give an interger number between 1 and 100 : ");
    scanf("%d",&n);

    while ( n < 1 || n > 100 )
    {
        printf("given value is wrong\ngive a new value between 1 and 100 : ");
        scanf("%d",&n);
    }
    return 0 ;
}

CodePudding user response:

Is there any way to define a variable for example that only accepts one values from 1 to 100?

No, not directly.


Alternative, form a struct and provide get and set functions. Information hiding. User can only set the variable using functions.

struct a1to100;
bool a1to100_set(struct a1to100 *a, val); // Return error flag.
int a1to100_read(struct a1to100 *a);      // Return 1 on success, EOF on end-of-file
int a1to100_get(const struct a1to100 *a); // Return value

struct a1to100 *a1to100_create(void);
void a1to100_free(struct a1to100 *a);

Or create a helper function to read an int sub-range. Sample:

int read_int_subrange(int min, int max, int value_on_eof) {
  char buf[100];
  printf("Give an integer number between %d and %d : ", min, max);

  while (fgets(buf, sizeof buf, stdin)) {
    char *endptr;
    errno = 0;
    long val = strtol(buf, &endptr, 0);
    if (endptr > buf && *endptr == '\n' && errno == 0 && val >= min && val <= max) {
      return (int) val;
    }
    printf("Given value is wrong\nGive a new value between %d and %d :\n", 
        min, max);
  }

  return value_on_eof;
} 
  •  Tags:  
  • c
  • Related