Forgot your password?

Interviews: Bjarne Stroustrup Answers Your Questions 102

Posted by samzenpus
from the listen-up dept.
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:
  • Shame (Score:4, Insightful)

    by The Evil Atheist (2484676) on Wednesday August 20, 2014 @10:26AM (#47712107) Homepage
    Shame a few of the questions are trying to guilt trip him into saying C++ was a mistake.
  • by Anonymous Coward on Wednesday August 20, 2014 @10:30AM (#47712155)

    There are obvously characters in the post that didn't appear properly.

    1980 called, and they want their HTML markup problems back.

  • by Dutch Gun (899105) on Wednesday August 20, 2014 @10:42AM (#47712249)

    From someone in the trenches using C++, I can definitely tell you that C++ 11/14 has made a massive difference, along with the adoption of better programming practices that have occasionally been eschewed by game programmers because of speed concerns. I describe the new C++ as feeling like C#, except with far uglier syntax. It's fantastic to be able to almost completely eschew the use of raw pointers (at least ones which I have to use to manage memory). It almost feels like the language has garbage collection, except that RAII + smart pointers work wonderfully on resources as well as memory.

    I've been working in what is essentially a version of C++ 98-compatible style for nearly my entire programming career. Modern hardware has really reached a point where game developers can effectively take advantage of some of the real advantages of modern C++. It's remarkable how much more productive you can be when you're not worrying about having to carefully manage memory, tracking down a ref-counted leak, or (worst of all) spending hours or even days searching for some memory stomp.

    Best of all, a some of the newer features don't even require a significant amount of overhead, but really just put more work on the compiler instead of the programmer. And there are ways to mitigate some of the downsides of ubiquitous RAII-type design (the cost of creating lots of small object), though custom memory managers optimized for those sorts of scenarios.

    I have to say, I agree with Bjarne's answers, especially his answer to the notion of dropping compatibility with older features. While it does make the language more complex to keep that cruft around, it's equally important to allow programmers to wrap up older libraries with newer interfaces, for example, and make sure the codebase still compiles cleanly. Since I started out on my own just a year and a half ago, I had the advantage of starting my game codebase from scratch, so I could use the most modern techniques, but I've worked at places with 10 to 15 year old codebases. There's just no way all of that is going to get rewritten in the near future, so backward compatibility is hugely important for the C++ community.

    Overall, C++ gets a lot of grief for it's ugly syntax and nasty gotchas, but modern techniques have really eliminated a huge percentage of those. Personally, I tend to view C++ like an extremely sharp kitchen knife. It can be a dangerous tool for novices, and you certainly don't want to use it when a butter knife will do, but there are some jobs that simply demand it.

  • by Dutch Gun (899105) on Wednesday August 20, 2014 @01:30PM (#47713589)

    D sounds like a neat language that I'll probably never be able to use. I'm a game developer, and C++ has a native compiler for every machine I would ever need my code to run on, as well as an already mature ecosystem (engines, code libraries, sample code, all in C++). In fact, C/C++ is pretty much the only option I have if I want my code to be broadly portable.

    It's interesting how a lot of languages don't seem worry too much about backward compatibility, because they want to focus on a clean and better language. Unfortunately, in the real world, there are always massive amounts of legacy code that need to continue to work alongside whatever new whizbang features are introduced, even at the expense of a cleaner or more elegant language.

    If I had to give any one reason for C++'s success, it would be the standards committee's stubborn (and in hindsight, wise) refusal to "clean up" the language by removing crufty features and syntax, a lot of which were leftover from C. C++ code from 20 years ago still compiles today mostly unchanged, and that's incredibly important when trying to build up or maintain a large ecosystem. You can see what a huge split it causes in the community when a language breaks compatibility like Python did (2.x vs 3.x), and ultimately, I wonder if it's more damaging than C++'s more conservative approach. As a developer, I'd be hesitant to heavily invest in a language that is more likely to break compatibility and leave me stranded.

Swap read error. You lose your mind.