0

Can anybody explain What is const int and How it works? It was used in the following code of the find.c

The program is as follows:

/** * Prompts user for as many as MAX values until EOF is reached, * then proceeds to search that "haystack" of values for given needle. * * Usage: ./find needle * * where needle is the value to find in a haystack of values */

include

include

include

include "helpers.h"

// maximum amount of hay const int MAX = 65536;

int main(int argc, string argv[]) { // ensure proper usage if (argc != 2) { printf("Usage: ./find needle\n"); return -1; }

// remember needle
int needle = atoi(argv[1]);

// fill haystack
int size;
int haystack[MAX];
for (size = 0; size < MAX; size++)
{
    // wait for hay until EOF
    printf("\nhaystack[%i] = ", size);
    int straw = get_int();
    if (straw == INT_MAX)
    {
        break;
    }

    // add hay to stack
    haystack[size] = straw;
}
printf("\n");

// sort the haystack
sort(haystack, size);

// try to find needle in haystack
if (search(needle, haystack, size))
{
    printf("\nFound needle in haystack!\n\n");
    return 0;
}
else
{
    printf("\nDidn't find needle in haystack.\n\n");
    return 1;
}

}

1 Answer 1

0

The const keyword signifies that the following declared variable is a constant. In other words, the value held by the variable cannot be changed by any operation during program execution. If the program attempts to change the value of a constant, the compiler will flag an error.

MAX was set as a constant because it holds a symbolic value. For example, MAX was used as the size value of the haystack array. If the value of MAX changed following the declaration of the array, then the loops would be left with a different value for processing the array. This could lead to some bugs, or even a segmentation fault.

It is wise to use constants in certain scenarios! Look into the #define directive and macro definitions for another method of creating constants.

2
  • Can it be used in the main?
    – Rahul
    Commented Mar 22, 2017 at 10:56
  • Or it should be outside main
    – Rahul
    Commented Mar 22, 2017 at 10:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .