0

I’m encountering a puzzling issue when using the assert macro in C++20 with std::map:
Code (Fails to Compile):

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<pair<int, int>, vector<int>> M0, M1;

    // Assertion fails to compile
    assert(M0[{1, 0}].size() == M1[{0, 1}].size());

    return 0;
}

Error Message:

error: macro "assert" passed 3 arguments, but takes just 1

Code (Compiles Successfully,Wrap the conditional statements in assert with ()):

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<pair<int, int>, vector<int>> M0, M1;

    // Assertion compiles successfully
    assert((M0[{1, 0}].size() == M1[{0, 1}].size()));

    return 0;
}

Does this mean that "assert" has a bug?

3
  • 2
    No, it does not have a bug. C pre-processor is a text processor. It looks at M0[{1, 0}].size() == M1[{0, 1}].size() and sees three text tokens: M0[{1 and 0}].size() == M1[{0 and 1}].size(), but assert(x) expects a single text token. Commented Dec 31, 2024 at 3:36
  • beyond the comma error, here the second piece of code contains a side effect in the assert (insertion when calling [] on a non-existent key) which seems to me to be avoided. Commented Dec 31, 2024 at 3:39
  • 2
    Side note: you should read Why should I not #include <bits/stdc++.h>? and What's the problem with "using namespace std;"?. Commented Dec 31, 2024 at 4:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.