cambelot
cambelot

Reputation: 165

"dimension" and "parameter" equivalent commands in C

I'm not too familiar with writing C but I'm currently translating some code from FORTRAN to C. I understand the meaning of both but I'm unsure how to write it in C. Here's a small clipping of my code in Fortran:

program main
      parameter (g=9.8,nx=102,ny=100,r13=1./3.,r23=2./3.)
      dimension u0(0:nx+1,0:ny+1,3),ux(0:nx+1,0:ny+1,3)
      dimension uy(0:nx+1,0:ny+1,3),uxx(0:nx+1,0:ny+1,3)
      dimension uxy(0:nx+1,0:ny+1,3),uyy(0:nx+1,0:ny+1,3)

Upvotes: 0

Views: 130

Answers (2)

John Bode
John Bode

Reputation: 123478

This is sort of close - assumes a C99 compiler or a C2011 compiler that supports variable-length arrays:

const double g = 9.8;
const int nx = 102;
const int ny = 100;
const double r13 = 1.0/3.0;
const double r23 = 2.0/3.0;

int main( void )
{
   int u0[nx+2][ny+2][3];
   int ux[nx+2][ny+2][3];
   int uy[nx+2][ny+2][3];
   int uxx[nx+2][ny+2][3];
   int uxy[nx+2][ny+2][3];
   int uyy[nx+2][ny+2][3];
   ...
}

Note that arrays in C don't allow arbitrary indexing; they always start from 0, so an N-element array is always indexed from 0 to N-1. Thus, if you want an array indexed from 0 to 103, you must declare the array size as 104.

If you're using a compiler that doesn't support VLAs, then array dimensions must be specified with compile-time constant expressions. Thus, nx and ny will have to be preprocessor macros instead of const-qualified variables, like so:

#define nx 102
#define ny 100

Declaring the other constants at file scope makes them visible to other translation units, which kind-of sort-of serves the same function as the PARAMETER statement.

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

parameter (g=9.8,nx=102,ny=100,r13=1./3.,r23=2./3.)

can be translated to #define statements.

#define g 9.8
#define nx 102
#define ny 100
#define r13 (1./3.)
#define r23 (2./3.)

And

dimension u0(0:nx+1,0:ny+1,3),ux(0:nx+1,0:ny+1,3)

can be translated to:

double u0[nx+2][ny+2][3];
double u1[nx+2][ny+2][3];

You have to very careful about the use of indices though. In FORTRAN, u0(0, 0, 3) is a valid item. In C, you have to use u0[0][0][2] to access the corresponding item.

Upvotes: 1

Related Questions