Home > database >  Is there any backlash to do comparison operator on constexpr, const, and non-const?
Is there any backlash to do comparison operator on constexpr, const, and non-const?

Time:10-03

Basically the title, I'm still learning C and want to know how this work.

example:

int i = 1;
const int ci = 2;
constexpr int cei = 1;

if (i != ci && i == cei)
cout<< i << endl;

Vs

int i = 1;
int ci = 2;
int cei = 1;

if (i != ci && i == cei)
cout<< i << endl;

Is there any difference?

CodePudding user response:

Yeah! there is difference between the two section you mentioned but in your context there is no difference in comparison because we are comparing both values not the type of variables so it will satisfy the equation.

If you want to make more depth discussion on your question then you can read the rest lines :

From the first you can see that you had used const int, it will throw an error if you'll try to assign other values to it because the values mentioned with const keyword can't be manipulated.

eg:-

#include <iostream>
using namespace std;
int main()
{
    const int a = 5;
    a = a 5;
    cout<<a;

    return 0;
}

This will throw an because error firstly we are declaring const and then manipulating it.

Error will be like : assignment of read-only variable ‘a’.

Now comming to constexpr indicates that the value, or return value, is constant and hence this will works as similar to the const keyword and will throw the same error if we'll manipulate it after defining.

But int without const or constexpr will be mutable and can be changed whenever we wants to change in the program.

Hope it helps!

  •  Tags:  
  • c
  • Related