Monday, 30 June 2014

Yet Another Difference Between C and C++: Initializing Constant Variables

  Constant variable initialization is yet another minute difference between C and C++. Consider the program given below.

int main()
  int x = 111;
  static int y = x;
  if(x == y)
     printf("Not Equal");
  return 0;

If you save the program as a C++ program, it compiles fine and shows the output as "Equal". But the same program when compiled as C will give you the following error "initializer element is not constant|". What is the reason? This is another minor difference between C and C++. In C a constant variable can only be initialized with a constant value and not by using another variable. But C++ do not have this restriction. You can initialize a constant variable with any other variable.

Click here to download the C++ program.

No comments:

Post a Comment