Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incompatibility between C and C++ code

The given C code

#include <stdio.h>
int x = 14; 
size_t check()
{
   struct x {};
   return sizeof(x); // which x
}
int main()
{
    printf("%zu",check()); 
    return 0;
}

gives 4 as output in C on my 32 bit implementation whereas in C++ the code

#include <iostream>
int x = 14;    
size_t check()
{
   struct x {};
   return sizeof(x); // which x    
}
int main()
{
    std::cout<< check(); 
    return 0;
}

outputs 1. Why such difference?

like image 842
Mohit Khullar Avatar asked Mar 19 '11 08:03

Mohit Khullar


People also ask

Is C code compatible with C++?

C++ is a subset of C as it is developed and takes most of its procedural constructs from the C language. Thus any C program will compile and run fine with the C++ compiler. However, C language does not support object-oriented features of C++ and hence it is not compatible with C++ programs.

What can C do that C++ cant?

On the other hand, C++ has tons of additional stuff that C can't do. Templates, polymorphism, operator overloading, etc, etc. C can mimic all of these things with different syntax, and there's no program you can write in one language that can't be written in the other language... so they're both equally capable.

Is C++ a strict superset of C?

C++ is a superset of C. All your C programs will work without any modification in this environment. However, we recommend that you get accustomed to new styles and techniques of C++ from day one.

Is C++ backwards compatible with C?

C++ is not fully backward compatible with C, wherever it's needed it has drawn a line.


1 Answers

In C++ class declaration struct x {}; introduces the name x into the scope of check and hides x (previously declared as int at file scope). You get 1 as the output because size of empty class cannot be zero in C++.

In C, an inner scope declaration of a struct tag name never hides the name of an object or function in an outer scope.You need to use the tag name struct to refer to the typename x (struct). However you can't have an empty struct in C as it violates the syntactical constraints on struct(however gcc supports it as an extension).

like image 144
Prasoon Saurav Avatar answered Oct 08 '22 23:10

Prasoon Saurav