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?
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.
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.
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.
C++ is not fully backward compatible with C, wherever it's needed it has drawn a line.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With