Find answers, ask questions, and connect with our <br>community around the world.

  • Posted by Orhan on September 18, 2022 at 3:46 pm


    Although I use const suffix, I get the result as 3 in both compiler flags -Wall and -Wall -Werror.

    I can’t move on to other videos because I couldn’t complete the homework.

    #include <iostream>
    int main()
    const int a = 3.14 ;
    std::cout << a << std::endl;
    return 0;


    terminal gives “3” output instead of 3.14

    Nishant replied 1 year, 7 months ago 2 Members · 1 Reply
  • 1 Reply
  • Nishant

    September 20, 2022 at 1:05 pm

    Hi Orphan-gng,

    In the recent developments of C++, dynamic type-casting is done by the compiler, so even if you declare a variable as int type and assign it a floating point value, compiler will implicitly convert it to an integer by truncating the decimal part. So when you output the value on terminal you will see the integer part.

    However when you add the const keyword and try to reassign the value, compilation with -Werror flag would result in an error. You can try compiling the code snippet below,


    int main(int argc, char *argv[])
    const int a = 3.14;

    std::cout << " a = " << a << std::endl; a = 3.27; // error: assignment of read-only variable ‘a’ std::cout << " a = << a << std::endl; return 0; } Hope that helps.

Log in to reply.

error: Content is protected !!