c++ – Incomprehensible expression sizeof (0) ["\ 0"]


Explain what this expression means and why it outputs 1?

#include <iostream>

int main() {
   std::cout << sizeof(0)["\0"] << '\n';   


sizeof is interesting and not what it seems. It evaluates the values ​​of the expression "virtually" to find out the type, and then returns its value. Let's repeat step by step with the compiler.

Original expression

std::cout << sizeof(0)["\0"] << '\n';   

First, add the correct parentheses

std::cout << sizeof((0)["\0"]) << '\n';   

And here the old sishnaya truth is hidden – a[b] == b[a] == *(a+b) . Let's rearrange.

std::cout << sizeof("\0"[0]) << '\n';   

Now it is obvious that there is just one character

std::cout << sizeof('\0') << '\n';   

And sizeof(char) in pluses is always according to the rules of 1.

Scroll to Top