Difference analysis between C++ and C

  • 2020-04-02 02:37:40
  • OfStack

Although C++ is backward compatible with C, there are many differences between C and C. This article gives a few examples to illustrate, but these are also very easy to ignore. This article only briefly lists a few examples, more differences readers still need to continue to explore and summarize in the study and practice.

C compiler passed but C++ compiler failed:

1. The compiler is not allowed to call a function before it is declared in C++, but it is allowed in C.


#include<stdio.h> //Please compile with GCC and g++ respectively
int main() 
{ 
  foo();   //Foo () is called before its declaration/definition
}  
 
int foo() 
{ 
  printf("Hello"); 
  return 0;  
} 
 

2. C++ cannot use a normal pointer to a constant, but C can.


#include <stdio.h> //Please compile with GCC and g++ respectively
  
int main() 
{ 
  int const j = 20;  
   
  int *ptr = &j;  
  printf("*ptr: %dn", *ptr); 
  return 0; 
} 

3, in C language, void pointer can be directly assigned to other types of Pointers, such as int *, char *, etc. But in C++, a void pointer must be cast explicitly. (the return value of the malloc function is of type void *)


#include <stdio.h> //Please compile with GCC and g++ respectively
int main() 
{ 
  void *vptr; 
  int *iptr = vptr; //C++ must use int *iptr = (int *) VPTR;
  return 0; 
} 

C and C++ output results are different:

4. Character constants are treated differently in C and C++ : in C, character constants such as 'a' and 'b' are treated as int, while in C++ they are treated as char. So, in C sizeof('A') is the same thing as sizeof(int), and the output is 4; Sizeof ('A') is still the same as sizeof(char) in C++, and the output is 1.


#include<stdio.h> //Please compile with GCC and g++ respectively
int main() 
{ 
 printf("%d", sizeof('a')); 
 return 0; 
} 

5. The 'struct' keyword must be used to define structures in C, but can be omitted in C++. In C++ local variables override global variables with the same name, but not in C.


#include <stdio.h> //Please compile with GCC and g++ respectively
int T; 
  
int main() 
{ 
  struct T { double x; };  
  printf("%d", sizeof(T)); //C output 4, C++ output 8
  return 0; 
} 

6. Boolean results are represented differently in C++ and C. Because C does not support booleans directly, it returns an int, while C++ returns a bool. So sizeof(1==1) is sizeof(int) in C and sizeof(bool) in C++.


#include <stdio.h> //Please compile with GCC and g++ respectively
 
int main() 
{ 
  printf("%dn", sizeof(1==1)); //C output 4, C++ output 1
  return 0; 
} 

This paper only makes a simple analysis and summary of the differences between C++ and C, I believe it will help you to better understand C and C++.


Related articles: