Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the most surprising elements of the C++ standard?

Tags:

c++

I've decided to get more acquainted with my favorite programming language, but only reading the standard is boring.

What are the most surprising, counter-intuitive, or just plain weird elements of C++? What has shocked you enough that you ran to your nearest compiler to check if it's really true?

I'll accept the first answer that I won't believe even after I've tested it. :)

like image 525
György Andrasek Avatar asked Oct 31 '09 23:10

György Andrasek


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

Does C have a runtime?

The venerable C language uses a runtime environment -- the C compiler inserts runtime instructions into the executable image (the compiled .exe file). The runtime instructions create runtime environments that can manage the processor, handle local variables and so on throughout the program's execution.


2 Answers

I found it somewhat surprising that

class aclass
{
public:
int a;
};

some_function(aclass());

will have ainitialized to 0 in some_function, while

aclass ac;
some_function(ac);

will leave it unitinitalized. If you explicitly define the default constructor of aclass:

class aclass
{
public:
aclass(): a() {}
int a;
};

then aclass ac; will also initialize a to 0.

like image 97
henle Avatar answered Nov 07 '22 08:11

henle


Another answer I could add would be the throw() qualifier. For example:

void dosomething() throw()
{
   // ....
}

void doSomethingElse() throw(std::exception)
{
  // ....
}

Intuitively, this seems like a contract with the compiler, indicating that this function is not allowed to throw any exceptions except for those listed. But in reality, this does nothing at compile time. Rather it is a run-time mechanism and it will not prevent the function from actually throwing an exception. Even worse, if an unlisted exception is thrown, it terminates your application with a call to std::terminate().

like image 32
Charles Salvia Avatar answered Nov 07 '22 06:11

Charles Salvia