+ 1

Two C++ Questions

Question 1: In a challenge, it says ## can also be used as a preprocessor other than just #. But I do ##include <iostream> and I get an error. Can someone explain it? Question 2: Can someone explain this C++ code: #include <iostream> using namespace std; void foo(int x) try{ int y=2; throw 1; } catch(int e) { cout << e << endl << x << endl; //how can it access x but not y? //cout << y << endl; //doesn't work? } int main() { foo(3); return 0; }

28th Mar 2021, 6:31 PM
Edward Finkelstein
Edward Finkelstein - avatar
2 Respuestas
+ 4
1. It is really also used by preporcessor, but has different role: https://docs.microsoft.com/en-us/cpp/preprocessor/token-pasting-operator-hash-hash?view=msvc-160 , https://www.cprogramming.com/reference/preprocessor/token-pasting-operator.html 2. It is because the code after `try` block and the code after the `catch (int)` are in different blocks and thus are using their own namespace (block of a code inside which the names are accessible and outside which are not (unless some spacial command like calling a function and passing variable values or addresses as arguments)) which is initially the same as the namespace of the parent block. You can try how it is actually working: declare and initialize a variable, then do something with it; now place the variable declaring and initializing into braces; now remove that braces and place them around the code which uses this variable. 3. Please, ask one question (or several hardly related to each other questions) per question.
28th Mar 2021, 6:38 PM
#0009e7 [get]
#0009e7 [get] - avatar
+ 4
Thanks Martin Taylor. I didn’t know about token pasting operator, thanks. Thanks get
28th Mar 2021, 7:23 PM
Edward Finkelstein
Edward Finkelstein - avatar