C++ equivalents of Fortran concepts

I wish there were a guide to modern C++ for modern Fortran programmers that discussed analogous concepts. It could programmers moving in either direction. I don’t know C++ well, but here are a few thoughts. There was a previous thread Fortran for C++ programmers ... guidelines?.

C++ now has modules, so you no longer need to write and #include header files.

C++ functions can declared constexpr, which remind me of pure functions in Fortran.

C++ functions can have const arguments, which can be intent(in) in Fortran.

C++ auto has type inference, similar to associate in Fortran.

C++ variables declared within braces have scope within those braces, similar to variables defined within block, end block in Fortran.

Here is a trivial C++ code using modules, followed by a Fortran analog.

math.cpp

export module math;

export constexpr int cube(const int n){
	return n*square(n);
}

// square() is not exported but can be used within module
constexpr int square(const int n){
	return n*n;
}

main.cpp

#include <iostream>
import math;

int main(){
	const auto n = 4;
	// line below invalid since square does not have export
	// attribute in module math
	// std::cout << "square of " << n << " is " << square(n) << "\n";
	std::cout << "cube of " << n << " is " << cube(n) << "\n";
}

compile with g++ -fmodules-ts math.cpp main.cpp

Fortran

module math
implicit none
private
public :: cube
contains
pure function cube(n)
integer, intent(in) :: n
integer             :: cube
cube = n*square(n)
end function cube
!
! square() is not exported but can be used within module
pure function square(n)
integer, intent(in) :: n
integer             :: square
square = n**2
end function square
end module math
!
program main
use math
implicit none
! line below invalid because square is not public in module math
! print*,"square of ",n," is",square(n)
associate (n => 4)
print*,"cube of ",n," is",cube(n)
end associate
end program main
1 Like

constexpr functions in C++ have particular semantics pertaining to compile-time computing for which there is no analog in Fortran in terms of nonintrinsic functions even though the standard includes certain intrinsic functions that can be consumed in constant expressions.

See this thread: there is great value in having the ability for a practitioner to author CONSTEXPR functions in Fortran that can yield rich dividends with scientific and technical computing. It will be helpful if more community members upvote the suggestion at the GitHub J3-Fortran site:

1 Like

I like the idea of juxtaposing the various programming constructs and concepts in this way, but my knowledge of C++ is too fragmentary and rudimentary to judge what the equivalents are. Just take the CONSTEXPR example - I would not have been able to pinpoint the difference as @FortranFan just did.

Yes, C++ does have concepts that can be thought as analogous to Fortran’s. I still think a Fortran module is better designed though, and the ability to declare modules as private is implemented as cleanest as it gets. constexpr doesn’t sound a bad idea anyway, and I do think that C++ has a few (and I mean very few) features Fortran should also have - better class destructors comes to mind, even though such a thing is much less needed in Fortran than in C++.

But, expanding the topic, I wonder what is the analog of Fortran’s superb array support… there ain’t such a thing in C++. Yes, you finally have stuff like std::vector<...> and std::array<...> at your disposal, but you still have to “teach” them how to do any arithmetic by operator overloading and long templates that tend to compile very slowly. And even if you stomach that, I doubt you will ever end up with a full Fortran equivalent. I don’t know about you, but that alone should suffice to stick with Fortran. And I didn’t even mention complex arithmetic or even worse, complex arrays - well, I just did.

The C++ experts don’t recommend using C-style multidimensional arrays. There are class libraries such as Armadillo and Eigen. In Discovering Modern C++, 2nd. ed. Gottschling mentions Blitz++, MTL4, and HPR-BLAS. I wonder what the risk is of using a C++ array library that stops being maintained.

For arrays in C++, the following works well:

https://www.math.ualberta.ca/~bowman/Array.html

Interestingly, its’ aim is to be ‘as fast as Fortran’.

I am aware there are libraries trying to address the problem, and I am sure you can find more of those mentioned. But does that really solve the problem? Relying on external software is not uncommon - we all do that, one way or another. But when you have to do it even for basic features such as arrays, then there is a problem. A big one.
Everything is… matrices. You see them everywhere, you need them everywhere. Numerical Analysis is literally full of them. Graphics are full of them. Even game programming is full of them. It’s not like you have a uncommon feature that might be useful for a very specific task, so it’s ok if the language lacks it and you must rely on external libraries - which may or may not suit your needs, may or may not being maintained tomorrow. It’s basic stuff that should be there day one, at least for a modern high-level programming language.
And I am not even talking about “sophisticated” constructs such as where a>0; s=1; elsewhere; s=-1; end where. One could argue this is a “luxury” they can live without (although I use it all the time.)

4 Likes

I agree with you. I mentioned this because @Beliavsky’s list didn’t contain it. For use with the fftw and the other things that they have built (implicitly dealiased convolutions), this class works nicely. But, yes, this also doesn’t give me things like A(:,i) = 1.0_dp (you have A.load(1.0)) that is trivial in Fortran.

For ordinary variable dummy arguments in C++ (neither references nor pointers) the comparison does not make much sense as the modification of the dummy (passed by value) would not change the actual arg anyway.

It is ok for reference arguments. Mostly true for pointer arguments also, although

void sub(const int *i)
{
  const int j=6;
  *i = 8;  // ILLEGAL, compiler error, as expected
  i = &j;  // Perfectly LEGAL, no equivalence in Fortran
  printf("%d\n", *i);
}
1 Like

There are plenty of Fortran libraries that have stopped being maintained, but we still use them. The C++ committee faces similar very problems as the Fortran one in terms of having to make compromises to remain (mostly) backward compatible. The build systems are the one which need maintenance if you ask me.

Not to open a new topic, I’ll ask it here: Do you know of some crash course of c++ for experienced Fortran programmers with basic knowledge of c? Ideally, it would be a list of equivalent simple codes in modern Fortran and c++. I have a bunch of routines in each of them that should work together. In total the code is not too long, so I’m trying to estimate what is cheaper, to look for the way to compile them together, or to translate the routines one way or another.

Many thanks!

@Niko, you may want to start by reviewing the information in this thread.

A quick suggestion will be to start with a book (e.g., by Pohl) or a university guide from their computing department (many available online) that are unfortunately dated to late 1990s for C++ for Fortran programmers. Then move on immediately to modern C++ (C++20 and C++23) books and materials in conjunction with modern Fortran and kinda develop a guide of your own interest. The work on LFortran can be of help to you.

Ultimately the call is yours keeping in mind your colleagues and your computing domain(s), etc. as to whether you want to proceed with either all C++ codebase or a mixed-language C++ and Fortran codebase.
Both are workable but the latter requires care , especially with C++ exception handling and with ensuring proper runtime and libraries that use C as the bridge layer. So many teams out there prefer the former. There are few circumstances now where it can be all Fortran.

If all that you are interested in are solutions to a common set of problems in C++ and Fortran then the notes I’ve written may be of interest.

They are here

I worked in Computing Services at King’s College, London and was responsible for the C++ training. Here are some of the people I provided training for.

Staff and research post graduates as part of the normal College training scheme;

MSc students in the Department of Mathematics doing an MSc in Financial
Mathematics;

MSc students in Computer Science;

MSc students in Electrical Engineering;

Undergraduates in Mechanical Engineering as a component of a second year examinable course;

Research post graduates in the Mechatronics and Medicine Group at Imperial College in London;

Staff at Oxford University;

Staff at the Numerical Algorithms Group, Oxford;

and also indirectly whilst teaching on a number of C++ courses for PTR in Wokingham, including people from Qinetiq, Vertu (I had no idea that a mobile phone could cost £850,000!), AWE, Met Office,
Virgin Media, RAF Waddington.

I keep the notes up to date, and the last set of changes was in November 2022.

YMMV

Ian Chivers

7 Likes

@cmaapic ,

Brilliant effort toward what is essentially a full-fledged book (perhaps you publish it as such?). A quick question: did you mean the title to be, “An Introduction to C++ Programming for Programmers”? Or, “… C++ Programming for Beginners”?

A general question is to what C++ standard your C++ codes should adhere. I just bought the 3rd edition of Stroustrup’s Tour of C++ to see what has been added in recent standards (not that I have mastered the earlier ones). His book has been suggested for programmers coming to C++ from another language.

Most of the people today already have some programming background, so for programmers really.

Thank you so much for pointing towards the other topic. I missed it completely. That’s exactly the information that I was looking for.

And thanks to the others for suggesting great sources! I got Stroustrup’s book and it looks very readable.

I’m getting “Not found” message when I click on the link that you left. Could you please check if the file is there or my firewall is doing something weird?

Many apologies. I’ve been having some difficulties configuring the site to make it accessible with
better security protocols. I’ll do some more work on this today and make another post when I’ve tested
the changes.

1 Like

I’ve altered some of the security settings. Would you like to try now?

1 Like