1

I've seen a piece of code that goes like this:

int charP[] = {
    ['A'] = 1, 
    ['B'] = 2,
    ['C'] = 3, 
    ['D'] = 4};

My syntax highlighter for C++ does not recognize it, but the syntax highlighter for C does. It sort of behaves like a Python dictionary, so charP['A'] would spit out 1. Maybe I'm not looking hard enough, but can anyone point me in the right direction because every time I search "C++ dictionary" or "C dictionary", it always involves Maps and not this. What is it? What are its limitations?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alden Luthfi
  • 105
  • 9
  • 1
    In c it's array initialization: https://en.cppreference.com/w/c/language/array_initialization using a designator. It's covered in section 6.7.9 of the c specification. – Allan Wind Jan 04 '23 at 04:38
  • 2
    More specifically, cppreference calls it a [designator](https://en.cppreference.com/w/c/language/array_initialization) – Nathan Pierson Jan 04 '23 at 04:38
  • 1
    *'C++ does not recognize it'* -- Because it's not valid syntax in C++ – Ranoiaetep Jan 04 '23 at 04:39
  • 2
    In C++ we call that nonsense. – Captain Obvlious Jan 04 '23 at 04:40
  • @Allan i had a read through the link you posted, but am not clear on how much memory is alocated by this thing. – Neil Butterworth Jan 04 '23 at 04:50
  • 4
    It's just a simple array of `int`, with all the entries set to 0, except the four that were specified. If ASCII encoding is being used, then `charP[65] = 1`, `charP[66] = 2`, `charP[67] = 3`, `charP[68] = 4`. Note that because the array size was not specified, the array is only large enough to contain the largest entry that was specified, so in this example, the array has 69 entries, indexed from 0 to 68. – user3386109 Jan 04 '23 at 04:50
  • 1
    Note that G++ (and probably Clang++ emulating G++) normally allows designated initalizers, even though it is not valid in standard C++. If you use `-pedantic` and/or `-pedantic-errors`, you should get told that the notation is not valid in standard C++. – Jonathan Leffler Jan 04 '23 at 04:52
  • @user33 thanks, that was what i guessed. a bit horrible, and i can see why it is not part of c++ – Neil Butterworth Jan 04 '23 at 05:02
  • @NeilButterworth Yes, it's something I generally avoid. And I certainly wouldn't leave the array size to chance. It would be `int charP[256] = ...` – user3386109 Jan 04 '23 at 05:07
  • if you are looking for python like dictionary .maps is equivalent to it in c++ – Hariom Singh Jan 04 '23 at 05:07
  • For a hashmap C++ has std::unordered_map. So code like that in C++ should look like this `std::unordered_map map {{'A',1}, {'B',2}};` – Pepijn Kramer Jan 04 '23 at 05:21

1 Answers1

5

In C it's array initialization using a designated initializer. It's covered in section 6.7.9 of the C 2017 specification.

In C++ it's invalid syntax (@Ranoiaetep, @CaptainObvlious).

Allan Wind
  • 23,068
  • 5
  • 28
  • 38