2

I'm new to C (well, RUSTY in C at least) and I'm working on some pre-ANSI C code in Visual Studio 2010. It compiles fine, but Intellisense is going crazy over the function declarations:

int add()
    int a, int b;
{
    return a + b;
}

instead of the ANSI

int add(int a, int b) 
{
    return a + b;
}

But I'm running into a few instances of arrays with bounds in function declarations, and I don't think that can be converted directly to ANSI C.

int add() 
    int a[5], int b[5];
{
    ...
}

The below compiles cleanly, but does this mean the exact same thing?

int add(int a[5], int b[5]) {
}
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
James Cronen
  • 5,715
  • 2
  • 32
  • 52

1 Answers1

4

Yes, it means the same thing, but it doesn't (and never did) really mean what it looked like it should mean.

The parameters are really pointers. By inference, there should be 5 elements in the arrays that they point to, but that isn't going to be guaranteed. In particular, given:

extern int add(int a[5], int b[5]);

int x[4];
int y[6];

add(x, y);

This is not going to cause the compiler to throw warnings.

With C99, you could let the optimizer assume that there will be at least 5 entries using the (weird) notation:

int add(int a[static 5], int b[static 5]) { ... }

Even this doesn't necessarily cause warnings at the call site; it is information to the compiler (though whether it uses it or not is up to the compiler).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Well, a compiler *could* issue a warning at the call site if it knows that the parameter provides access to an array shorter than 5 elements. But it's not guaranteed to do so (the behavior is undefined). (And gcc doesn't warn.) – Keith Thompson Sep 26 '13 at 20:16
  • So would it be more accurate to translate the offending statements with unbounded arrays? `int add(int a[], int b[]) { ... }` I'm pretty sure the program doesn't completely care what the size is. – James Cronen Sep 26 '13 at 20:27
  • It would as accurate to translate them with empty array bounds. The program should care about how big the arrays are; it won't be safe unless it knows how much space is available for it to use. The syntactic issue is that the bounds specified in the prototype or argument list are really not germane (for 1D arrays, or vectors -- they're crucial for `add_2d(int n, int a[][10], int b[]10])` to add `n` rows of `a` and `b`, which are both arrays such as `int a[20][10];`). – Jonathan Leffler Sep 26 '13 at 21:10