Thread: const

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    82

    const

    where do i need to use const and where not? i know that const indicates that the values can't be changed but i have seen examples, where i wouldn't use const but it's used and i can't figure out why.
    for instance, on this example, for mean function, why is the array const but for median it isn't? or in mode freq isn't const but answer[] is? why for bubbleSort we don't use const? why is printArray's parameter const?

    Code:
    1 /* Fig. 6.16: fig06_16.c2 This program introduces the topic of survey data analysis.
    3 It computes the mean, median and mode of the data */
    4 #include <stdio.h>
    5 #define SIZE 99
    67
    /* function prototypes */
    8 void mean( const int answer[] );
    9 void median( int answer[] );
    10 void mode( int freq[], const int answer[] ) ;
    11 void bubbleSort( int a[] );
    12 void printArray( const int a[] );
    13
    14 /* function main begins program execution */
    15 int main( void )
    16 {
    17 int frequency[ 10 ] = { 0 }; /* initialize array frequency */
    18
    19 /* initialize array response */
    20 int response[ SIZE ] =
    21 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,
    22 7, 8, 9, 5, 9, 8, 7, 8, 7, 8,
    23 6, 7, 8, 9, 3, 9, 8, 7, 8, 7,
    24 7, 8, 9, 8, 9, 8, 9, 7, 8, 9,
    25 6, 7, 8, 7, 8, 7, 9, 8, 9, 2,
    26 7, 8, 9, 8, 9, 8, 9, 7, 5, 3,
    27 5, 6, 7, 2, 5, 3, 9, 4, 6, 4,
    28 7, 8, 9, 6, 8, 7, 8, 9, 7, 8,
    29 7, 4, 4, 2, 5, 3, 8, 7, 5, 6,
    30 4, 5, 6, 1, 6, 5, 7, 8, 7 };
    31
    32 /* process responses */
    33 mean( response );
    34 median( response );
    35 mode( frequency, response );
    36 return 0; /* indicates successful termination */
    37 } /* end main */
    38
    39 /* calculate average of all response values */
    40 void mean( const int answer[] )
    41 {
    42 int j; /* counter for totaling array elements */
    43 int total = 0; /* variable to hold sum of array elements */
    44
    45 printf( "%s\n%s\n%s\n", "********", " Mean", "********" );
    46
    47 /* total response values */
    48 for ( j = 0; j < SIZE; j++ ) {
    49 total += answer[ j ];
    50 } /* end for */
    51
    52 printf( "The mean is the average value of the data\n"
    53 "items. The mean is equal to the total of\n"
    54 "all the data items divided by the number\n"
    55 "of data items ( %d ). The mean value for\n"
    56 "this run is: %d / %d = %.4f\n\n",
    57 SIZE, total, SIZE, ( double ) total / SIZE );
    58 } /* end function mean */
    59
    60 /* sort array and determine median element's value */
    61 void median( int answer[] )
    62 {
    63 printf( "\n%s\n%s\n%s\n%s",
    64 "********", " Median", "********",
    65 "The unsorted array of responses is" );
    66
    67 printArray( answer ); /* output unsorted array */
    68
    69
    70
    71 printf( "\n\nThe sorted array is" );
    72 printArray( answer ); /* output sorted array */
    73
    74 /* display median element */
    75 printf( "\n\nThe median is element %d of\n"
    76 "the sorted %d element array.\n"
    77 "For this run the median is %d\n\n",
    78 SIZE / 2, SIZE, );
    79 } /* end function median */
    80
    81 /* determine most frequent response */
    82 void mode( int freq[], const int answer[] )
    83 {
    84 int rating; /* counter for accessing elements 1-9 of array freq */
    85 int j; /* counter for summarizing elements 0-98 of array answer */
    86 int h; /* counter for diplaying histograms of elements in array freq */
    87 int largest = 0; /* represents largest frequency */
    88 int modeValue = 0; /* represents most frequent response */
    89
    90 printf( "\n%s\n%s\n%s\n",
    91 "********", " Mode", "********" );
    92
    93 /* initialize frequencies to 0 */
    94 for ( rating = 1; rating <= 9; rating++ ) {
    95 freq[ rating ] = 0;
    96 } /* end for */
    97
    98 /* summarize frequencies */
    99 for ( j = 0; j < SIZE; j++ ) {
    100 ++freq[ answer[ j ] ];
    101 } /* end for */
    102
    103 /* output headers for result columns */
    104 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",
    105 "Response", "Frequency", "Histogram",
    106 "1 1 2 2", "5 0 5 0 5" );
    107
    108 /* output results */
    109 for ( rating = 1; rating <= 9; rating++ ) {
    110 printf( "%8d%11d ", rating, freq[ rating ] );
    111
    112
    113
    114
    115
    116
    117
    118 /* output histogram bar representing frequency value */
    119 for ( h = 1; h <= freq[ rating ]; h++ ) {
    120 printf( "*" );
    121 } /* end inner for */
    122
    123 printf( "\n" ); /* being new line of output */
    124 } /* end outer for */
    125
    126 /* display the mode value */
    127 printf( "The mode is the most frequent value.\n"
    128 "For this run the mode is %d which occurred"
    129 " %d times.\n", modeValue, largest );
    130 } /* end function mode */
    131
    132 /* function that sorts an array with bubble sort algorithm */
    133 void bubbleSort( int a[] )
    134 {
    135 int pass; /* pass counter */
    136 int j; /* comparison counter */
    137 int hold; /* temporary location used to swap elements */
    138
    139 /* loop to control number of passes */
    140 for ( pass = 1; pass < SIZE; pass++ ) {
    141
    142 /* loop to control number of comparisons per pass */
    143 for ( j = 0; j < SIZE - 1; j++ ) {
    144
    145 /* swap elements if out of order */
    146 if ( a[ j ] > a[ j + 1 ] ) {
    147 hold = a[ j ];
    148 a[ j ] = a[ j + 1 ];
    149 a[ j + 1 ] = hold;
    150 } /* end if */
    151 } /* end inner for */
    152 } /* end outer for */
    153 } /* end function bubbleSort */
    154
    155 /* output array contents (20 values per row) */
    156 void printArray( const int a[] )
    157 {
    158 int j; /* counter */
    159
    160 /* output array contents */
    161 for ( j = 0; j < SIZE; j++ ) {
    162
    163 if ( j % 20 == 0 ) { /* begin new line every 20 values */
    164 printf( "\n" );
    165 } /* end if */
    166
    167 printf( "%2d", a[ j ] );
    168 } /* end for */
    169 } /* end function printArray */

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by lmanukyan
    for instance, on this example, for mean function, why is the array const but for median it isn't?
    This is probably a mistake for median. In both cases, the function does not need to modify the elements of the array, so the pointer should be a pointer to const.

    Note that there is a small bug in median: if there is an even number of elements, the median is the arithmetic mean of the two middle elements.

    Quote Originally Posted by lmanukyan
    or in mode freq isn't const but answer[] is?
    Because answer is an "input parameter" (also known as "in parameter") whereas freq is an "output parameter" (also known as "out parameter").

    Quote Originally Posted by lmanukyan
    why for bubbleSort we don't use const?
    Because the sort is an in-place sort, i.e., it modifies the elements of the array to sort it.

    Quote Originally Posted by lmanukyan
    why is printArray's parameter const?
    There is no need to modify the elements of an array to print them.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You should define a variable as const when it won't require changes. This affects parameters to functions because they are variables, too.
    for instance, on this example, for mean function, why is the array const but for median it isn't?
    Well, you can find the average of any mean without changing the order of the elements in the array. The median function isn't completely implemented, but a median is only defined on a sorted range. So when you call bubble sort with the array, which doesn't treat the array as const, the effect will percolate to this function.

    Bubble sort can't treat its array parameter as const because it has to swap elements to change the original order. At some level, it would be similar to trying to call this function:
    Code:
    void broken_swap (const void *const a, const void *const b)
    {
        const void *const temp = a;
        a = b;
        temp = a;
    }
    
    In function 'broken_swap':
    Line 4: error: assignment of read-only location
    Line 5: error: assignment of read-only variable 'temp'
    But see Question 6.9.

    Generally it is good to be const correct. It makes it easier to prove that a program has the desired workings when it is analyzed, because the compiler can enforce that a given variable won't be changed. On the other hand, constness is pervasive: once something is const, everything that uses that variable must also qualify it as constant.

  4. #4
    Registered User
    Join Date
    Nov 2015
    Posts
    82
    In median, what if we don't know whether the size of the array is even or odd? So it shouldn't be const, right? And, what do you mean by "to modify the elements"? Change the values of elements, change their order. What else?

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    In median, what if we don't know whether the size of the array is even or odd? So it shouldn't be const, right?
    It can be const. You can use a constant in a read-only way; that is the point. For example assume ArraySize is an integer constant:
    Code:
    if ( ArraySize % 2 == 0 ) printf ("%d is even\n", ArraySize);
    And, what do you mean by "to modify the elements"? Change the values of elements, change their order. What else?
    Nothing else.

    Another way to look at const: imagine you are writing a compiler. You need to enforce const variables in the code files your program will read. It turns out that a simple way to make sure variables stay const is to make sure that they never appear on the left hand side of an assignment. If you think carefully, this explains why a lot of statements are then illegal.
    Code:
    const int N = 42;
    N--, --N; /* unfolded: N = N - 1; */
    N++, ++N; /* unfolded: N = N + 1; */
    
    const int array[5] = { 0, 1, 2, 3, 4 };
    array[0]++; /* unfolded: array[0] = array[0] + 1; */
    
    const int temp = array[0];
    array[0] = array[1];
    array[1] = a;
    /* constant on left-hand side */
    This is the biggest help in understanding const that I personally know. I hope it works for you.
    Last edited by whiteflags; 01-02-2016 at 08:45 AM.

  6. #6
    Registered User
    Join Date
    Dec 2015
    Posts
    68
    where do i need to use const and where not? i know that const indicates that the values can't be changed but i have seen examples...

    C is also used in embedded mcu, were there is more read-only flash than ram.
    So while omitting the const the code still work but you're wasting valuable ram.
    Putting a non-changing value in flash and of course the compiler would have to warn that you are trying the change it as the hardware don't even allow for it.

    A compiler in high-balanced-optimize will figure a lot of this out by itself and inline const var in to the asm code itself or move it to flash as it is never changed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-20-2011, 01:19 PM
  2. Replies: 3
    Last Post: 11-15-2009, 04:57 AM
  3. Replies: 1
    Last Post: 04-03-2009, 08:52 AM
  4. Replies: 7
    Last Post: 04-28-2008, 09:20 AM
  5. Mutable members in const member functions still const
    By ripper079 in forum C++ Programming
    Replies: 3
    Last Post: 10-23-2002, 08:56 AM