Thread: Question: Const var defining another const var

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    2

    Question: Const var defining another const var

    Hi there.

    Could anyone please explain to me why, when I compile the following code with GCC I got an error?
    Code:
    Code:
    #include <stdio.h>
    
    const int CONSTANT_1 = 3;
    const int CONSTANT_2 = CONSTANT_1 + 2;
    
    int main (void) {
    
        printf("Constant 2 is: %d\n", CONSTANT_2);
    
        return 0;
    }
    The error I got is:
    "test_const.c:4:1: error: initializer element is not constant
    const int CONSTANT_2 = CONSTANT_1 + 2;"

    When I run it in CLANG it works fine.

    It also work (in GCC and CLANG) when in declare the constants inside the main function.

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    See top answers here and here.

  3. #3
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    I must admit I thought that would be valid integer constants... I'm a little disappointed that an integer constant isn't really "constant". I think I read somewhere that using an enum type is better than using "const" in these cases, but I have to admit I've not ran into this problem myself...

  4. #4
    Registered User
    Join Date
    Nov 2016
    Posts
    2
    Thanks for the answer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-20-2011, 01:19 PM
  2. question about const pointers and const ints
    By WarDoGG in forum C Programming
    Replies: 9
    Last Post: 01-08-2011, 02:11 PM
  3. Replies: 3
    Last Post: 11-15-2009, 04:57 AM
  4. Replies: 1
    Last Post: 04-03-2009, 08:52 AM
  5. Defining const in a class
    By g4j31a5 in forum C++ Programming
    Replies: 5
    Last Post: 11-20-2006, 11:27 AM

Tags for this Thread