Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!


Forgot your password?

Interviews: Bjarne Stroustrup Answers Your Questions 102

Last week you had a chance to ask Bjarne Stroustrup about programming and C++. Below you'll find his answers to those questions. If you didn't get a chance to ask him a question, or want to clarify something he said, don't forget he's doing a live Google + Q & A today at 12:30pm Eastern.
Cutting features and old syntax?
by Katatsumuri

Sometimes well-established languages keep adding new features and syntactic constructs until most developers are not even aware of all the possibilities and use maybe 20% in their usual daily work. The old features and syntax are kept around for compatibility and to keep the old guard content, even if cutting them would lead to faster compilation, more elegant language and less confusion.

This may be part of the reason for the constant introduction of new trendy languages with radically simplified syntax and libraries... Which then follow the same pattern. Few languages are introducing new paradigms, many are trying to be a "better" C++, Java, LISP, JavaScript or Perl.

Do you think this cycle is inevitable, or could it be a good idea to sometimes clean up the syntax and the obscure features in new specification versions, to keep the established languages more competitive?

Bjarne: Languages grow. The alternative is stagnation because there is nothing the maintainer of a large code base hates more than working code breaking – even if that code is full of avoidable errors. We dream of cleaning up the mess, but somehow there is never the month or couple of years needed. I dream of “cleaning up the mess” as much as the next guy, and I know the mess better than most. It is hard to evolve a language compatibly, but IMO it is harder still to make a major – worthwhile – breaking change. Stagnation is not something I can accept – we can and must do better (even if that takes compromises).

You probably didn’t mean that, but “syntax” isn’t the most important aspect of software development. People will suffer atrocious syntax to get valuable functionality (C++ template meta-programming is an example). Also, developers and maintainers of production code eventually tire of cute (often very terse) syntax. “Syntax” is the user-interface for programmers, rather than the system itself. What we hope for is a minimal and logical interface to a useful semantics.

For any reasonable definition of “paradigm” (a words I use only very rarely), there are very few new paradigms coming along, so people have to be happy with incremental changes. Slow steady progress can – over time – add up to major improvements. However, few people take the longer (decades) view.

On the evolution of C++
by stox

How do you feel about the evolution of C++ since it was first implemented with Cfront? What began as a pretty straightforward language has been expanded to significant complexity. Has this evolution been positive, or has it been an attempt to make the language apply to too many possible applications?

Bjarne: C++14 is a far better tool for software development than “C with Classes” was, far more powerful in the key areas that “C with Classes” was invented to deal with. It is more expressive, better checked, generates faster code, and is applicable in areas that “C with Classes” could not touch. The cost has been complexity. My aim has been constant: a direct mapping to hardware plus zero-overhead abstraction. C++ is not the best language for everyone and everything, but then I never promised that it would be. However, C++ is an excellent tool for attacking a vast variety of system design and implementation problems.

I hope that the tide has turned so that C++ is becoming more “novice friendly.” C++11 and C++14 are steps on that route: auto, range-for, lambdas, uniform initialization, concepts, etc., all makes it easier to express simple things simply (without loss of performance). For example, a friend sent me this C++99 code (simplified, of course, but from a large code base):

// old code:

std::vector::const_iterator cit = MemVec.cbegin();
for ( ; cit != v.end(); ++cit) {
if (LookForPatterm(*cit))
return true ;
return false;

He deemed this to be somewhat messy and in need of improvement. For starters, we can eliminate the long type name by letting auto deduce it:

// first step:

for (auto cit = MemVec.cbegin(); cit != v.end(); ++cit) {
if (LookForPatterm(*cit))
return true ;
return false ;

auto is the oldest C++11 feature. I implemented in in 1983/84, but was forced to remove it for C compatibility reasons. It provides the ability to deduce a type from and initializer; after all, the compiler knows the type of MemVec.cbegin() so why should I need to repeat it? Note how the scope of cit is now limited to its area of use.

We can simplify regular loops using a range-for, so we get:

// second simplification:

for (const auto& x : v)
if (LookForPatterm(x))
return true ;
return false ;

There is now no iterator, so it cannot be accidentally or deliberately modified in the loop. Now it is obvious that we should have used a standard-library algorithm:

// good:

return find_if(cbegin(v), cend(v), LookForPattern) != v.cend() ;

That’s where my friend stopped, observing that it was now also obvious how to use a lambda as the operation in other places. Being a fan of range/container algorithms, I would have said:

// my variant:

return find_if(v,LookForPattern)!=v.cend();

This involves having a range version of find_if lying around somewhere. For example:

// range version of std::find_if:

Iterator find_if(Cont& c, Pred p)
return std::find_if(begin(c),end(c),p);

Next time such an improvement is needed, I think my friend and his colleagues will jump directly to one of the later variants. With a bit of luck, they will even have tool to help them find candidates for simplification.

by Anonymous Coward

What do you regret most in C++ and how would you like to change it?

Bjarne: No regrets! Seriously, a language grows up at a specific time and in a specific environment. To survive that language has to be viable at every stage of its evolution. I’d hate to second guess 1980s vintage Bjarne. He was at least as smart as I am and had a far better grasp of the world at the time. Simply saying, “if I had had a few million dollars for buying market share with ‘free’ libraries or for developing a better definition of templates C++ would have been better” just isn’t intellectually honest.

If I had a time machine, I just might jump back to 1987 and drop a sketch of a design of templates with concepts on Bjarne’s desk. He was working on the template design at the time and knew the problems with template parameter requirements well. Unfortunately, neither he nor anyone else at the time knew how to simultaneously get generality, performance, and well-specified interfaces. Given a bit of help from the time traveler, he might very well have gotten the point. Then, in 1990, we would have been able to write:

void sort(Sortable& c); // sort random-access sequences of elements with
void user(vector& vs, vector>& vc)

// OK
sort(vc); // error: vs not Sortable; complex does not have }

However, I don’t have a time machine, so we had to wait until next year (or now if you use the concepts branch of GCC).

Future of C++ Standard Library
by DaphneDiane

One of the recent concerns raised with C++ compared to other popular languages is the breadth of the standard library. I know that the C++ standard committee was looking at adding a C++ transformed version of Cairo to the standard. And of course there is boost. What else do you see coming to address the perceived API shortcomings?

Bjarne: C++ is a formally standardized language. It is defined by the ISO. Compared to other such languages, C++ has a huge and growing standard library. However, compared by commercially owned languages, such as Java and C#, the ISO C++ standard library is tiny. We – the C++ standards committee – do not have the resources to buy market share. The committee is trying to add useful libraries as fast as it can safely do so. The standard library is most important because it creates a common foundation, but it can never be sufficient for the needs of the huge community.

We somehow have to create a better “exchange” for open-source and other libraries. We will also have to work harder on library interoperability. There are a huge number of C++ libraries “out there,” but they tend not to be designed for interoperability and many producers of libraries have their very own programming styles and specialized assumptions.

To speed up standardization – especially the standardization of libraries – the ISO C++ standards committee has started “study groups” producing “technical specifications.” A technical specification is not a full-blown international standard, but it is a document produced by the order of 20 people and approved by the full committee. Current library TSs in progress are:

File system
Library foundation (e.g., optional and string_view)
Ranges (for people tired of saying v.begin(),v.end() and much, much more)
Concurrency (threads, etc.)
Parallelism (parallel algorithms, networking, and more)
Numerics (incl. SIMD)
Transactional Memory (has core language parts)
I/O (incl. 2D graphics)
See here for details.

by gbjbaanb

Do you think that one thing holding C++ back is the lack of a standardized binary interface?

Currently if I want to make a module that can be consumed by others (whether than is others using a different language, or a different C++ compiler, or even just to use a pre-built module without sources) I have to export everything as C and use its (de-facto if nothing else) binary standard.

I think an ABI for C++ would increase its "real world" attractiveness considerably with little, if any, overhead. Do you agree, or are there issues around this that make it a significant challenge (apart from vendor adoption of course).

Bjarne: A C++ ABI would be a huge boon to the C++ community, however, it is not an easy problem to solve technically and most C++ implementation providers have a huge user bases that would howl in outrage if binary compatibility with their previous version was broken.

To solve the technical problem, we would need the ABI to cover basic object layout (easy), class hierarchies (not hard), and abstractions using templates (hard). An ABI that could not handle std::vector, std::map, and similar user-supplied abstractions would be a failure. I do not (in any detail) know how to do that.

To solve the political problem, we would need all vendors on a platform to adopt that ABI (probably impossible except in the longer term) or provide it as an “exchange format” in addition to their traditional ABI.

Which feature would you add to C++?
by jonwil

If you could add one feature to C++ (either the language or the standard library) and have it adopted in the C++ standard and supported by all the compilers etc., what would it be and why?

Bjarne: Ah! Just one feature? You must be kidding, but I’ll say “concepts.” They will change the way people think of generic programming and of programming in general, and we’ll have them next year. They are already shipping in a branch of GCC and will be an ISO C++ TS (Technical Specification) in 2015 (I hope and expect).

People have mentioned more standard libraries and a standard ABI. I’d like to see higher-level concurrency models –the type-safe C++11 threads and locks are still too low level. I’d like to eliminate the need for the visitor pattern workaround; for example, see:

Y. Solodkyy, G. Dos Reis and B. Stroustrup: Open Pattern Matching for C++. ACM GPCE'13.
Y. Solodkyy, G. Dos Reis, and B. Stroustrup: Open and Efficient Type Switch for C++. Proc. OOPSLA'12.
P. Pirkelbauer, Y. Solodkyy, and B. Stroustrup: Open Multi-Methods for C++. ACM GPCE’07.

Remember that an academic paper plus an implementation does not add up to a complete standards proposal, but wouldn’t you like to be able to write:

bool intersect(virtual Shape&, virtual Shape&); // non-member virtual function

void user(Shape& s1, Shape& s2)
if (intersect(s1,s2)) //

Assuming suitable overloads of intersect() to handle Shapes that are Circles, Triangles, etc. The alternative today is a mess of if-statements, some clever special-purpose workaround, or an elaborate visitor setup.

C++ without the C
by kthreadd

Apple recently introduced a language they call Swift or Objective-C without the C. It is technically a completely different language from Objective-C though. When C++ started out it had the major benefit that it was (mostly) compatible with C which at the time was immensely popular, making it trivial to mix new C++ code with existing C code. Today C is still a popular language but not as widely used as it once was. Assuming that C++ could drop C compatibility, how would you take that opportunity to improve C++?

Bjarne: People tend to underestimate C. Today, we probably don’t need C compatibility (except to keep billions of lines of critical code running), but we do need a direct map to hardware. If we didn’t have C or the C-level subset of C++, we would have to find a different way to do that map. Languages without C’s problems typically rely on C or C++ to do their dirty work for them.

I think we should think more about isolating unsafe code in a program than to eliminate it. Putting the necessary unsafe code into a different language limits our control of it, limits what can be communicated to it, and typically imposes overheads.

That said, when people rail against C, and by implication C++, they usually (and correctly in case of C and C-style C++) point to two problems: lack of type safety and the lack of abstraction mechanisms. Together, those two problems leave people with lots and lots of low-level code in which bugs can hide (e.g., buffer overflows, invalid pointers, and resource leaks).

C++ attacks these problems by providing alternatives. You can write type-safe code in C++; you can write simple code that doesn’t leak or leave invalid pointers behind; you can do so with zero overhead compared to lower-level alternatives. Consider:

vector collect(const string& terminator)
vector res;
for (string s; cin>>s && s!=terminator; )
return res;

void user() { auto ss = collect("end"); // ss is a vector

I used C++11’s move semantics and auto to simplify that code. Note the absence of memory management code and the absence of leaks. Returning containers by value is simple and efficient in C++11 because the standard library provide move constructors for all containers, such as vector.

The problem is that many people don’t write such simple code and are stuck with the old problems hidden in lots of far more complicated code.

I don’t actually think that there is less C and C++ programming these days. I think that in absolute terms there is more than ever, and not just people working on “legacy code.” People are confused by unscientific estimates of usage and especially by the fact that there is much more software development these days, so that the amount of C and C++ is declining relative to the total. In particular, I think I see significant growth of C++ in its core domains. The number of C++ programmers today is more likely to be 4 or 5 million than the 3 million I estimated ten years ago. But it is hard to count programmers.

Hour of Code
by Orestesx

What is your opinion of the "Hour of Code" as promoted by CSEdWeek? Does it trivialize computer science education?

Bjarne: I guess that anything that popularizes hands-on software development experience is good. On that count, I’m in favor of Lego, programming contests, Raspberry Pie, etc. Too many people think science and (especially) engineering boring.

Do color change and explosive chemistry experiments trivialize chemistry? Do demonstrations of Newton’s cradle and prisms trivialize physics? No! You need to inspire and motivate students in preparation for the necessary hard work. I think Computer Science should be taught as a serious academic discipline – like Physics and Biology – for which years of work is needed for mastery, rather than as a basic skill that must be quickly mastered by all. I think the serious work should start in high school, like it is (or IMO should be) for mathematics, physics, and biology. It is not just child’s play. It could start in university if it wasn’t that students tend not to choose fields of study in university that they have not encountered in high school.

Not everybody can become a good programmer. The world needs a lot of programmers, maybe 20 million, but we don’t need a billion. We need to distinguish between the education of professionals and giving people a bit of computer literacy. People seem confused about this or unwilling to accept that serious preparation is needed for people who build serious software. Our lives and livelihood depends on software. Just think of the amount of computing that goes into delivering your food to your table: agriculture, transport, telecommunications, embedded systems, planning, scheduling, etc. You cannot milk a herd of cows without the help of computers these days! Or at least you cannot if you have to keep records of the cows’ health and production for the obligatory quality control. I would strongly prefer for critical software to be developed and maintained by professionals. I’m less concerned about the quality of your favorite videogame or the advertisements that pop up to annoy me when I try to read the news.

I’m more interested in the engineering part of computer science than the pure science part. Computer science is among other things a set of science-based practical skills, an engineering discipline.

Personal programming projects
by kthreadd

Apart from work, do you have any personal programming projects going on? Which type of programming do you like most and is there a particular project that you would like to implement?

Bjarne: I tend to look at three kinds of code: code that creates trouble in the context of the C++ standard (subtle cases and proposals), small experiments with programming techniques, and production code. This implies looking on a lot of libraries and writing lots of small examples. Unfortunately, my “day job” plus my standards work do not leave time for significant personal projects.

Code rejuvenation
by SansEverything

You speak a lot about code rejuvenation and bringing old code to new standards. As you are working on C++14, many compilers do not fully support C++11 yet. In the past, it was even worse. Don't you think that this lack of feature support from compilers is a major problem and the biggest obstacle to code rejuvenation?

Bjarne: No. C++11 and/or C++14 implementation availability is not a major problem. Both are getting remedied fast, faster than I would have believed a couple of years ago. The adoption of C++11 is far faster than the C++98 adoption was. Waiting a year or two is not a significant problem in this context. There is plenty of work that can be done today.

When I talk about “rejuvenation” (some people call it “modernization” or “upgrading”), I mean rewriting large amounts of code written in styles known to complicate comprehension, hide bugs, and hinder optimization. I’m thinking of C-style code, code overusing class hierarchies, and some examples of complex template metaprogramming. Such code also tend to prevent newer, better, and simpler techniques to be used in newer code. The reason is partly that the need interoperate with such code messes up new code, partly that programmers steeped in the old style are reluctant to believe that the newer techniques work.

For example, I’d like to replace uses of arrays and pointers with std::arrays and vectors. I’d like to eliminate macros. I’d like to replace old-style for loops with range-for loops. I’d like to eliminate overuse of free store (heap). I’d like to break up large functions into smaller and more precisely defined ones. I’d like to replace ad hoc code with algorithms. I’d like to replace hand-crafted containers with standard-library ones. If I can, I’d like to eliminate race conditions and increase the amount of concurrency. I want to do all that without adding run-time overheads.

Typically, we cannot afford to rewrite the old code by hand. So when I talk about rejuvenation, I focus on (static) code analysis and code transformation: we must automate the rejuvenation process as far as possible. The reason I don’t refer to this as “refactoring” is that I’m typically not interested in a process that produces 100% compatible code. Some of the transformations I want require human attention. I want major improvement, not bug compatibility. People are working to produce such tools.
This discussion has been archived. No new comments can be posted.

Interviews: Bjarne Stroustrup Answers Your Questions

Comments Filter:

Karl's version of Parkinson's Law: Work expands to exceed the time alloted it.