0

for example:

int a[] = {1,2};
cout << (bool) a;
output: 1

this because the pointer that points to the first element is not a null pointer

but this confuses me :

int a[0];
cout << (bool) a;
output: 1

how this will be 1 and how there is a pointer that not null and there is no elements in array ?

I want a detailed explanation how a zero-length array is allocated in memory.

  • 1
    You are (C-style) casting a pointer to a bool. Might not be what you intended to do. – JHBonarius Mar 11 '22 at 12:27
  • 1
    zero size array is an extension... – Jarod42 Mar 11 '22 at 12:27
  • 4
    In Standard C++, the size of an array must be a constant expression and **must** be **greater than** `0`. – Jason Mar 11 '22 at 12:28
  • 1
    `a != nullptr` in both cases... so `true` displayed as 1. – Jarod42 Mar 11 '22 at 12:28
  • 1
    `a` is not a pointer. Thus, it can't be a null pointer. `(bool) a` is equivalent to `(bool) &a[0]`, and the result of `&` can't be a null pointer, either (except in `&*p`, when `p` is a null pointer). – molbdnilo Mar 11 '22 at 12:54
  • 3
    if you are using gcc then try to compile the code with the `-pedantic-errors` flag https://godbolt.org/z/sbj649Kcs. For compiler extensions you need to read your compilers manual – 463035818_is_not_an_ai Mar 11 '22 at 12:57
  • @molbdnilo • I thought `&*p` is **undefined behavior** when `p` is `nullptr`. (Maybe I'm mistaken, and there's a special clause in the standard to allow this kind of code.) – Eljay Mar 11 '22 at 14:00
  • @Eljay My memory might be wrong, but I believe the combinations `&*` and `*&` are specifically defined as no-ops (unless anything has been overloaded, of course). But I might also be confusing this with C... – molbdnilo Mar 11 '22 at 14:04

0 Answers0