2

Is there a way to declare array elements without typing each and every single one?? I'm creating an array of characters for the alphabet to be used for comparing and typed each and every single character is there a way to declare the elements like for example int array[50] = {from 1 to 50};

//from
char alphabet[30] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
//to this
char alphabet[30] = {'a' to 'z'};
//or is it possible for integers or float?
wohlstad
  • 12,661
  • 10
  • 26
  • 39
nubDev
  • 19
  • 2

1 Answers1

0

I recommend to just use a for loop:

for (int i = 0; i < 26; i++) {
    alphabet[i] = 'a' + i;
}

This works with every datatype.

Tenobaal
  • 637
  • 1
  • 16
  • This is not guaranteed to work. – Jason Nov 02 '22 at 10:46
  • How high is the chance, that he will try to use this program on a machine or environment that uses some weird encoding? – Tenobaal Nov 02 '22 at 10:51
  • 2
    I would even say that this is guaranteed not to work because you won't enter the loop. Also, using `i <= alphabet.size()` instead might lead to unexpected behavior if you don't size `alphabet` correctly. For instance, with OP's given example, `alphabet.size() == 30` and your loop will add unwanted characters into `alphabet` – DrosvarG Nov 02 '22 at 10:51
  • I accidentally wrote 0 instead of 26, fixed it now – Tenobaal Nov 02 '22 at 10:54
  • At this point, you might aswell use Jason Liam's suggestion and type `char alphabet[] = "abcdefghijklmnopqrstuvwxyz";` as this loop become extremely specific. It would make your code both less error-prone and more readable – DrosvarG Nov 02 '22 at 10:58
  • 1
    Actually, no, this does not always work. There are real-world standardised character sets for which characters in the latin alphabet (`'a'` to `'z'`) are not a contiguous set i.e. there are other (non-alphabetic) characters between `'a'` and `'z'`. A similar comment applies for uppercase letters too. – Peter Nov 02 '22 at 11:15
  • Maybe improvable with something like `static_assert(('a'+1)=='b');` ? – MatG Nov 02 '22 at 11:33
  • @MatG - still insufficient. There are character sets for which `'a' + 1 == 'b'` but subsequent groups of letters are not contiguous. – Peter Nov 04 '22 at 00:42
  • @Peter Ehmm, `('a'+25)=='z'`? (lol) – MatG Nov 04 '22 at 18:33
  • @MatG That isn't guaranteed for the same reason. You're still assuming that the set `'a'` to `'z'` is contiguous. – Peter Nov 05 '22 at 00:39