Navigation

Sunday 14 October 2018

Can const data type replace #define in C programming ?

I hear people say that const can replace #define and has more edges.
#include <stdio.h>
#define ROW 3
#define COL 4 
int sum2d(int r, int c, int (*a)[c]);
int main(void)
{
    const int row = 3;
    const int col = 4;
    int junk[row][col] = {{2, 4, 6, 8}, {3, 5, 7, 9}, {12, 10, 8, 6}};
    printf("Sum = %d\n", sum2d(row, col, junk));

    return 0;
}
int sum2d(int r, int c, int (*a)[c])
{
    int total = 0;
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            total += a[i][j];
    return total;
}
Look at the above code which fails to be compiled.
Error message which I fail to understand:
test.c:9:2: warning: excess elements in array initializer [enabled by default]
test.c:9:2: warning: (near initialization for junk[0]’) [enabled by default]
test.c:9:2: warning: excess elements in array initializer [enabled by default]
test.c:9:2: warning: (near initialization for junk[0]’) [enabled by default]
test.c:9:2: warning: excess elements in array initializer [enabled by default]
test.c:9:2: warning: (near initialization for junk[0]’) [enabled by default]
test.c:9:2: warning: excess elements in array initializer [enabled by default]
I thought it would work but it didn't.
#include <stdio.h>
#define ROW 3
#define COL 4 
int sum2d(int r, int c, int (*a)[c]);
int main(void)
{
    const int row = 3;
    const int col = 4;
    int junk[ROW][COL] = {{2, 4, 6, 8}, {3, 5, 7, 9}, {12, 10, 8, 6}};
    printf("Sum = %d\n", sum2d(row, col, junk));

    return 0;
}
int sum2d(int r, int c, int (*a)[c])
{
    int total = 0;
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            total += a[i][j];
    return total;
}
After changing junk[row][col] to junk[ROW][COL], it can be successfully compiled and work.
Why const int fails to work in this example?
Can't const data type  replace #define  in C programming?

Here

3 comments:

  1. Did you try using const size_t instead of const int as the type for the array index?

    ReplyDelete
    Replies
    1. Tried it. Not working. Same warnings.

      Delete
    2. I tried to compile your example with g++ on Cygwin, using -std=c++11.
      The compiler protested against the declaration "int sum2d(int r, int c, int (*a)[c])" (I think you're using a nonstandard extension here) but after removing this, the example compiled just fine. Maybe you should report this behavior to the compiler manufacturer...

      Delete