On stack overflow I ran into a question What is ":-!!" in C code?
> #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
> #define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
out of curiosity I want to know how can I use these kind of macros ?
int main()
{
BUILD_BUG_ON_ZERO(0);
return 0;
}
In the above code it gives an error that type name is not allowed.
EDIT :
the code compiles on linux using gcc but fails on visual studio
Read the best answer carefully:
The macro is somewhat misnamed; it should be something more like
BUILD_BUG_OR_ZERO, rather than ...ON_ZERO
So it fails to compile when the parameter is nonzero:
int main()
{
BUILD_BUG_ON_ZERO(1);
return 0;
}
http://ideone.com/TI97r3
As for a practical usage:
int main()
{
BUILD_BUG_ON_ZERO(sizeof(int) != 4); // we need int to be 4 bytes, stop compilation otherwise
return 0;
}
As for C++: this is a C construct that does not compile in C++ at all.
In C++11 you can use a static_assert instead.
Related
Note: There are a number of questions on Stack Overflow with very similar-looking titles, but none that I have found is actually a duplicate, IMHO.
I have been using code like the following in my project(s) for a number of years, without problem. However, since a recent update to Visual Studio 2019 (16.7.2 - though it may have been at 16.7.1), the MSVC compiler has started to generate the error shown (I have the compilation 'Standard' set to C++17).
#include <iostream>
class Foo {
public:
Foo() { }
static constexpr char Letters[6][10] = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot" };
};
int main()
{
Foo f;
for (int i = 0; i < 6; ++i) std::cout << f.Letters[i] << std::endl;
return 0;
}
Error (at the opening brace in the constexpr line):
error C2131: expression did not evaluate to a constant message :
failure was caused by a read of an uninitialized symbol
The clang-cl compiler continues to accept the code without any warning.
I have a fairly 'trivial' fix for this issue, as below:
class Foo {
public:
Foo() { }
inline static const char Letters[6][10] = { "Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot" };
};
However, I am intrigued by the error report. Is there something I am missing (and have been missing for ~5 years), or is this a bug in the latest release of MSVC? If the former, what is my error or invalid assumption?
For example, suppose we have a string like:
string x = "for(int i = 0; i < 10; i++){cout << \"Hello World!\n\";}"
What is the simplest way to complete the following function definition:
void do_code(string x); /* given x that's valid c++ code, executes that code as if it were written inside of the function body */
The standard C++ libraries do not contain a C++ parser/compiler. This means that your only choice is to either find and link a C++ compiler library or to simply output your string as a file and launch the C++ compiler with a system call.
The first thing, linking to a C++ compiler, would actually be quite doable in something like Visual Studio for example, that does indeed have DLL libraries for compiling C++ and spitting out a new DLL that you could link at runtime.
The second thing, is pretty much what any IDE does. It saves your text-editor stuff into a C++ file, compile it by system-executing the compiler and run the output.
That said, there are many languages with build-in interpreter that would be more suitable for runtime code interpretation.
Not directly as you're asking for C++ to be simultaneously compiled and interpreted.
But there is LLVM, which is a compiler framework and API. That would allow you to take in this case a string containing valid C++, invoke the LLVM infrastructure and then afterwards use a LLVM-based just in time compiler as described at length here. Keep in mind you must also support the C++ library. You should also have some mechanism to map variables into your interpreted C++ and take data back out.
A big but worthy undertaking, seems like someone might have done something like this already, and maybe Cling is just that.
Use the Dynamic Linking Loader (POSIX only)
This has been tested in Linux and OSX.
#include<fstream>
#include<string>
#include<cstdlib>
#include<dlfcn.h>
void do_code( std::string x ) {
{ std::ofstream s("temp.cc");
s << "#include<iostream>\nextern \"C\" void f(){" << x << '}'; }
std::system( "g++ temp.cc -shared -fPIC -otemp.o" );
auto h = dlopen( "./temp.o", RTLD_LAZY );
reinterpret_cast< void(*)() >( dlsym( h, "f" ) )();
dlclose( h );
}
int main() {
std::string x = "for(int i = 0; i < 10; i++){std::cout << \"Hello World!\\n\";}";
do_code( x );
}
Try it online! You'll need to compile with the -ldl parameter to link libdl.a. Don't copy-paste this into production code as this has no error checking.
Works for me:
system("echo \"#include <iostream> \nint main() { for(int i = 0; i < 10; i++){std::cout << i << std::endl;} }\" >temp.cc; g++ -o temp temp.cc && ./temp");
In c++03 and earlier to disable compiler warning about unused parameter I usually use such code:
#define UNUSED(expr) do { (void)(expr); } while (0)
For example
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
return 0;
}
But macros are not best practice for c++, so.
Does any better solution appear with c++11 standard? I mean can I get rid of macros?
Thanks for all!
You can just omit the parameter names:
int main(int, char *[])
{
return 0;
}
And in the case of main, you can even omit the parameters altogether:
int main()
{
// no return implies return 0;
}
See "ยง 3.6 Start and Termination" in the C++11 Standard.
There is the <tuple> in C++11, which includes the ready to use std::ignore object, that's allow us to write (very likely without imposing runtime overheads):
void f(int x)
{
std::ignore = x;
}
I have used a function with an empty body for that purpose:
template <typename T>
void ignore(T &&)
{ }
void f(int a, int b)
{
ignore(a);
ignore(b);
return;
}
I expect any serious compiler to optimize the function call away and it silences warnings for me.
To "disable" this warning, the best is to avoid writing the argument, just write the type.
void function( int, int )
{
}
or if you prefer, comment it out:
void function( int /*a*/, int /*b*/ )
{
}
You can mix named and unnamed arguments:
void function( int a, int /*b*/ )
{
}
With C++17 you have [[maybe_unused]] attribute specifier, like:
void function( [[maybe_unused]] int a, [[maybe_unused]] int b )
{
}
Nothing equivalent, no.
So you're stuck with the same old options. Are you happy to omit the names in the parameter list entirely?
int main(int, char**)
In the specific case of main, of course, you could simply omit the parameters themselves:
int main()
There are also the typical implementation-specific tricks, such as GCC's __attribute__((unused)).
What do you have against the old and standard way?
void f(int a, int b)
{
(void)a;
(void)b;
return;
}
Macros may not be ideal, but they do a good job for this particular purpose. I'd say stick to using the macro.
The Boost header <boost/core/ignore_unused.hpp> (Boost >= 1.56) defines, for this purpose, the function template boost::ignore_unused().
int fun(int foo, int bar)
{
boost::ignore_unused(bar);
#ifdef ENABLE_DEBUG_OUTPUT
if (foo < bar)
std::cerr << "warning! foo < bar";
#endif
return foo + 2;
}
PS C++17 has the [[maybe_unused]] attribute to suppresses warnings on unused entities.
There's nothing new available.
What works best for me is to comment out the parameter name in the implementation. That way, you get rid of the warning, but still retain some notion of what the parameter is (since the name is available).
Your macro (and every other cast-to-void approach) has the downside that you can actually use the parameter after using the macro. This can make code harder to maintain.
I really like using macros for this, because it allows you better control when you have different debug builds (e.g. if you want to build with asserts enabled):
#if defined(ENABLE_ASSERTS)
#define MY_ASSERT(x) assert(x)
#else
#define MY_ASSERT(x)
#end
#define MY_UNUSED(x)
#if defined(ENABLE_ASSERTS)
#define MY_USED_FOR_ASSERTS(x) x
#else
#define MY_USED_FOR_ASSERTS(x) MY_UNUSED(x)
#end
and then use it like:
int myFunc(int myInt, float MY_USED_FOR_ASSERTS(myFloat), char MY_UNUSED(myChar))
{
MY_ASSERT(myChar < 12.0f);
return myInt;
}
I have my own implementation for time critical segments of code.
I've been researching a while a time critical code for slow down and have found this implementation consumes about 2% from the time critical code i have being optimized:
#define UTILITY_UNUSED(exp) (void)(exp)
#define UTILITY_UNUSED2(e0, e1) UTILITY_UNUSED(e0); UTILITY_UNUSED(e1)
#define ASSERT_EQ(v1, v2) { UTILITY_UNUSED2(v1, v2); } (void)0
The time critical code has used the ASSERT* definitions for debug purposes, but in release it clearly has cutted out, but... Seems this one produces a bit faster code in Visual Studio 2015 Update 3:
#define UTILITY_UNUSED(exp) (void)(false ? (false ? ((void)(exp)) : (void)0) : (void)0)
#define UTILITY_UNUSED2(e0, e1) (void)(false ? (false ? ((void)(e0), (void)(e1)) : (void)0) : (void)0)
The reason is in double false ? expression. It somehow produces a bit faster code in release with maximal optimization.
I don't know why this is faster (seems a bug in compiler optimization), but it at least a better solution for that case of code.
Note:
Most important thing here is that a time critical code slow downs without above assertions or unused macroses in release. In another words the double false ? expression surprisingly helps to optimize a code.
windows.h defines UNREFERENCED_PARAMETER:
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
So you could do it like this:
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
Or outside of Windows:
#include <stdio.h>
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
i am using the Borland c++ 3.1 compiler. I want to work with exceptions, i've written the following code:
void main (void) {
int a = 0;
int b = 1;
int c;
try {
throw 1;
}
catch(int a) {
b = a;
}
}
The compiler returns a syntax error. what's wrong?
Most compilers will issue an error stating that your main function must return an int.
The main function must return int in a C++ program. It's unsafe to return void from a main function and many modern compilers won't compile. Aside from that everything looks compilable
Following code fails with a error message :
t.cpp: In function `void test()':
t.cpp:35: error: expected primary-expression before '>' token
t.cpp:35: error: expected primary-expression before ')' token
Now I don't see any issues with the code and it compiles with gcc-4.x and MSVC 2005 but not with gcc-3.4 (which is still quite popular on some platforms).
#include <string>
#include <iostream>
struct message {
message(std::string s) : s_(s) {}
template<typename CharType>
std::basic_string<CharType> str()
{
return std::basic_string<CharType>(s_.begin(),s_.end());
}
private:
std::string s_;
};
inline message translate(std::string const &s)
{
return message(s);
}
template<typename TheChar>
void test()
{
std::string s="text";
std::basic_string<TheChar> t1,t2,t3,t4,t5;
t1=translate(s).str<TheChar>(); // ok
char const *tmp=s.c_str();
t2=translate(tmp).str<TheChar>(); // ok
t3=message(s.c_str()).str<TheChar>(); // ok
t4=translate(s.c_str()).str<TheChar>(); // fails
t5=translate(s.c_str()).template str<TheChar>(); // ok
std::cout << t1 <<" " << t2 <<" " << t3 << " " << t4 << std::endl;
}
int main()
{
test<char>();
}
Is it possible to workaround it on the level of translate function and message class, or maybe my code is wrong, if so where?
Edit:
Bugs related to template-functions in GCC 3.4.6 says I need to use keyword template but should I?
Is this a bug? Do I have to write a template keyword? Because in all other cases I do not have to? And it is quite wired I do not have to write it when I use ".c_str()" member function.
Why gcc-4 not always an option
This program does not starts when compiled with gcc-4 under Cygwin
#include <iostream>
#include <locale>
class bar : public std::locale::facet {
public:
bar(size_t refs=0) : std::locale::facet(refs)
{
}
static std::locale::id id;
};
std::locale::id bar::id;
using namespace std;
int main()
{
std::locale l=std::locale(std::locale(),new bar());
std::cout << has_facet<bar>(l) << std::endl;
return 0;
}
And this code does not compiles with gcc-4.3 under OpenSolaris 2009- broken concepts checks...
#include <map>
struct tree {
std::map<int,tree> left,right;
};
As mentioned elsewhere, that seems to be a compiler bug. Fair enough; those exist. Here's what you do about those:
#if defined(__GNUC__) && __GNUC__ < 4
// Use erroneous syntax hack to work around a compiler bug.
t4=translate(s.c_str()).template str<TheChar>();
#else
t4=translate(s.c_str()).str<TheChar>();
#endif
GCC always defines __GNUC__ to the major compiler version number. If you need it, you also get __GNUC_MINOR__ and __GNUC_PATCHLEVEL__ for the y and z of the x.y.z version number.
This is a bug in the old compiler. Newer GCC's, from 4.0 to (the yet unreleased) 4.5, accept it, as they should. It is standard C++. (Intel and Comeau accept it also.)
Regarding cygwin and opensolaris, of course gcc-3.4 is not the only option: the newer versions (the released 4.4.3, or the unreleased 4.5 branch) work fine on these OS'es. For cygwin, it's part of the official distribution (see the gcc4* packages in the list). For opensolaris, you can compile it yourself (and instructions on how to do so can easily be found with Google).
I would try to use a different workaround, since adding the template disambiguator there is incorrect and will break if you move to a different compiler later on.
I don't know the real code, but passing a regular std::string seems to work (option 1: avoid converting to const char * just to create a temporary) or you could provide an overloaded translate that takes a const char* as argument (if the compiler does not complain there), depending on your requirements.