I'm studying c++ namespace and i made a simple code to understand it. In particular i made this code and i don't understand why it doesn't give me the compiler error that i'have already decleare the variable 'a'. Is the compiler help me in some way?  #include&lt;iostream&gt; using namespace std; namespace funzioni_e_altro {     int a=5;     int b=20;     int c=10; } int main() {     using namespace funzioni_e_altro;     int a=0;     cout&lt;&lt;funzioni_e_altro::a&lt;&lt;"\n";     cout&lt;&lt;b&lt;&lt;"\n";     cout&lt;&lt;a&lt;&lt;"\n";  return 0; }   I expect it gave me a compiler error, but it gave me the outputs:  5  20  0
120889
How can I access a shadowed global variable in C? In C++ I can use :: for the global namespace.
119176
In some text it is given that we can't assign constant values to a reference variable. When I executed such a program I could do it. Is there any condition we can't assign a constant value to a reference variable?
12352
I just came onto a project with a pretty huge code base.   I'm mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.    if (!!variable &amp;&amp; (!!api.lookup("some-string"))) {        do_some_stuff();  }                                      I know these guys are intelligent programmers, it's obvious they aren't doing this by accident.   I'm no seasoned C++ expert, my only guess at why they are doing this is that they want to make absolutely positive that the value being evaluated is the actual boolean representation. So they negate it, then negate that again to get it back to its actual boolean value.   Is this correct, or am I missing something?
43165
Both uses of the \let primitive often lead to the same result. Is this even true for every case? What was the thought process behind it. And if they are actually not equivalent, are there particular situations in which you can only use one or the other?  Addendum  Summary  As your plenty and nice answers show, there are cases in which you clearly have to respect one of the variations (for instance regarding assignments to '=' and macros that check for spaces). These were totally understandable points and they explain a lot. Now, @Werner's answer confirmed one ingenuous thought of mine:     "The use of = is purely to emphasize the fact that an assignment is being made [...]"   Moreover Knuth himself seem to have intended the synopsis including the '=', though he also used the other way. Why did he include it then? It will probabilly have to do with the exact meaning of the TeX source snippet cited by @Werner. To be honest, I don't know WEB either, but if there is someone who does, can he explain it (in very easy terms) by adding an edit to his answer? New answers are clearly welcome too.  Side Note  As an element of a gray area I found an example where using the syntax including the equal sign causes "difficulties":  If you have control sequences which need the 'csname-expandafter' mechanism, and you want to stick to the minimal exploitation of \expandafter by saying  \expandafter\let\csname foo1\expandafter\endcsname\csname bar1\endcsname   you can't add an equal sign because it would distract TeX from reading the \expandafters correctly. To get the equal sign work you would need to use the slightly unhandier version  \expandafter\let\csname foo1\expandafter\endcsname\expandafter=\csname bar1\endcsname
73156
I usually never see test for new in C++ and I was wondering why.  Foo *f = new Foo;  // f is assumed as allocated, why usually, nobody test the return of new?
42864
I mean other than using it when required for functions, classes, if, while, switch, try-catch.  I didn't know that it could be done like .  In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."  What other uses are there besides those mentioned?   Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly?   How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?
92846
I just learned about the C++ construct called "placement new".  It allows you to exactly control where a pointer points to in memory.  It looks like this:   #include &lt;new&gt;        // Must #include this to use "placement new"  #include "Fred.h"     // Declaration of class Fred   void someCode()  {    char memory[sizeof(Fred)];    void* place = memory;     Fred* f = new(place) Fred();   // Create a pointer to a Fred(),                                   // stored at "place"     // The pointers f and place will be equal     ...  }    (example from ) In this example, the this pointer of Fred will be equal to place.    I've seen it used in our team's code once or twice.  In your experience, what does this construct enable?  Do other pointer languages have similar constructs?  To me, it seems reminiscent of equivalence in FORTRAN, which allows disparate variables to occupy the same location in memory.
98249
While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.  The C++ code looks something like this:  #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt;  using namespace boost::python;  int main(int, char **)  {     Py_Initialize();      try      {         object module((handle&lt;&gt;(borrowed(PyImport_AddModule("__main__")))));          object name_space = module.attr("__dict__");         object ignored = exec("from myModule import MyFunc\n"                           "MyFunc(\"some_arg\")\n",                           name_space);          std::string res = extract&lt;std::string&gt;(name_space["result"]);     }      catch (error_already_set)      {         PyErr_Print();     }      Py_Finalize();     return 0; }   A (very) simplified version of the Python code looks like this:  import thirdparty  def MyFunc(some_arg):     result = thirdparty.go()     print result   Now the problem is this:  'MyFunc' executes fine, i can see the print of 'result'. What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace. I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.
37260
In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks.  For example, the following code does not compile:  try {   String s = "test";   // (more code...) } catch {   Console.Out.WriteLine(s);  //Java fans: think "System.out.println" here instead }   In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block.  (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".)  The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block:  String s; try {   s = "test";   // (more code...) } catch {   Console.Out.WriteLine(s);  //Java fans: think "System.out.println" here instead }   However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally).  My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)?
67578
I haven't written any C++ in years and now I'm trying to get back into it. I then ran across this and thought about giving up:  typedef enum TokenType {     blah1   = 0x00000000,     blah2   = 0X01000000,     blah3   = 0X02000000 } TokenType;   What is this? Why is the typedef keyword used here? Why does the name TokenType appear twice in this declaration? How are the semantics different from this:  enum TokenType {     blah1 = 0x00000000,     blah2=0x01000000,     blah3=0x02000000 };
45776
I'm trying to do something like the following:  enum E;  void Foo(E e);  enum E {A, B, C};   which the compiler rejects.  I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why.  Can anyone explain?  Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as  enum E {     FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X }   as project X is not something I want my users to know about.  So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.  As for the compiler - it's GCC.
46741
In some code I've inherited, I see frequent use of size_t with the std namespace qualifier.  For example:  std::size_t n = sizeof( long );   It compiles and runs fine, of course.  But it seems like bad practice to me (perhaps carried over from C?).  Isn't it true that size_t is built into C++ and therefore in the global namespace?  Is a header file include needed to use size_t in C++?  Another way to ask this question is, would the following program (with no includes) be expected to compile on all C++ compilers?  size_t foo() {     return sizeof( long ); }
1371
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference?  A (quite pointless) example in Java:  a) declaration before loop:  double intermediateResult; for(int i=0; i &lt; 1000; i++){     intermediateResult = i;     System.out.println(intermediateResult); }   b) declaration (repeatedly) inside loop:  for(int i=0; i &lt; 1000; i++){     double intermediateResult = i;     System.out.println(intermediateResult); }   Which one is better, a or b?   I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.  Edit: I am especially interested in the Java case.
109393
Consider the following code:  template&lt;class T&gt; class Foo { public:   Foo() { a = 1; }  protected:   int a; };  template&lt;class T&gt; class Bar : public Foo&lt;T&gt; { public:   Bar() { b = 4; };    int Perna(int u);  protected:   int b;  };  template&lt;class T&gt; int Bar&lt;T&gt;::Perna(int u)  {    int c = Foo&lt;T&gt;::a * 4; // This works   return (a + b) * u;    // This doesn't }   g++ 3.4.6, 4.3.2 and 4.1.2 give error   test.cpp: In member function `int Bar&lt;T&gt;::Perna(int)': test.cpp:25: error: `a' was not declared in this scope   g++ 2.96 and MSVC 6, 7, 7.1, 8 and 9 accept it, as do (at least) older Intel and SGI c++ compilers.   Do the new Gnu C++ compiler obey the standard or not? If they do, what is the rationale behind that inheriting class is not able to see a protected inherited member variable?  Also, if there's  int A() { return a; }    in Foo, I get error  test.cpp:25: error: there are no arguments to A that depend on a template parameter, so a declaration of A must be available test.cpp:25: error: (if you use -fpermissiveâ, G++ will accept your code, but allowing the use of an undeclared name is deprecated)   when I try to use it in a member function of Bar. I find that curious as well: Bar inherits Foo, so I think it's obvious that A() in scope of Bar is Foo::A().
32521
I came across this strange code snippet which compiles fine:  class Car {     public:     int speed; };  int main() {     int Car::*pSpeed = &amp;Car::speed;     return 0; }   Why does C++ have this pointer to a non-static data member of a class? What is the use of this strange pointer in real code?
52606
For example, how to avoid writing the 'func_name' twice?  #ifndef TEST_FUN #  define TEST_FUN func_name #  define TEST_FUN_NAME "func_name" #endif   I'd like to follow the  rule.  Version of C preprocessor:  $ cpp --version cpp (GCC) 4.1.2 20070626 (Red Hat 4.1.2-14)
96500
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...   using namespace xyzzy   ...statements in them, which impact on my code when I least want or expect it.  Is there a way I can somehow cancel/override a previous "using" statement to avoid this.  Maybe...  unusing namespace xyzzy;