Unusual Error: expected unqualified-id before ')' token - c++

I am trying to take a list data type I created and make it a template. In doing so I've run into the following obscure problem. I can post all of the code if needed, but this is really the function that is causing the problem.
Note: This code was compiling just fine until I got to this method. I was compiling after writing every few lines as a sanity check, and everything was fine, but then I get to this point and it blows up. If I take the try/catch block out of this method it compiles just fine, so I'm pretty sure the problem is isolated there, not a missing semicolon in a header/etc. as reported from other answers -- though I did of course triple-check to be sure! :)
Here's the code that is causing the problem:
template<class T>
bool UnsortedListType<T>::IsFull()
{
try { return false; }
catch(std::bad_alloc exception) { return true; } // line 35
}
Like I said, I simplified it as much as possible while still triggering the error. Here is the error:
UnsortedListType.cpp||In member function 'bool UnsortedListType<T>::IsFull()':
UnsortedListType.cpp|35|error: expected type-specifier
UnsortedListType.cpp|35|error: expected unqualified-id before 'exception'
UnsortedListType.cpp|35|error: expected ')' before 'exception'
UnsortedListType.cpp|35|error: expected '{' before 'exception'
UnsortedListType.cpp|35|error: 'exception' was not declared in this scope
UnsortedListType.cpp|35|error: expected ';' before ')' token
Everything I can find on this error says the problem is either an extra semicolon or a missing semicolon, either in the header or this file. I can't find an instance of either. And if I remove the try/catch block, it compiles fine.
Plus, if I catch an int, it compiles just fine:
template<class T>
bool UnsortedListType<T>::IsFull()
{
try { return false; }
catch(int exception) { return true; }
}
I can also catch(int) and it will compile just fine, but if I try to catch(std::bad_alloc) (i.e. with no "exception" variable name) it throws the same error listed above. Even if I try simply catch(std::exception) it fails to compile.
So now I'm stumped. I'm not an expert at C++ by any stretch, this is for a class, and I'm not sure how to get past this error.
Incidentally, here's the code from the non-generic version, which also compiles just fine, and is verbatim from the textbook I'm using (Dale, if anyone wonders):
bool UnsortedListType::IsFull() const
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch (std::bad_alloc exception)
{
return true;
}
}
I am using CodeBlocks 12.11 IDE on Windows 7 with the built-in GNU compiler.
Any help appreciated, and I'll be happy to post more code if requested, I just didn't want to fill the page up.
Many thanks in advance.
PS I should state, yes I am doing homework, but the homework doesn't call for me to make a template, I am choosing to go that route myself. Not sure if it has any relevance, but this is the first time I've used C++ templates, so just tossing that out there.

std::bad_alloc is defined in the header <new>, so you need to include that.
Also, it's better to catch exceptions by reference. Catching by value causes a copy, perhaps sliced, of the exception object to be made. Personally I make non-const reference a habit, allowing exception state to be added during handling, but most basic exception types are stateless so there's no practical difference between const & and non-const &.

Related

Unable to compile a simple C++17 program

I am trying to use C++17 if constexpr feature but fail to compile a simple function.
Code:
template <auto B>
int foo()
{
if constexpr(B)
{
return 1;
}
else
{
return 2;
}
} // <- I get an error here
int main()
{
return foo<false>();
}
The error output by compiler:
<source>(12): error #1011: missing return statement at end of non-void function "foo<B>() [with B=false]"
}
Used -std=c++17 -O3 -Wall -Werror compiler flags and icc 19.0.1 compiler.
Is this valid C++17 code?
What is the reason behind this error?
Is this valid C++17 code?
Yes, it's valid. Exactly one return statement will be discarded, while the other will remain. Even if none remain, C++ still allows you to omit a return statement from a function. You get undefined behavior if the function's closing curly brace is reached, but that's a risk only if execution reaches that point.
In your case, execution cannot reach such a point, so UB is not possible.
What is the reason behind this error?
You used -Werror, thus turning the compiler's false positive warning into a hard error. One workaround is to disable this warning around that particular function. This is purely a quality of implementation problem.

Unit testing a vector string

I have this really simple line of code in my production-code(A.cpp) as follows:
std::string A::getString(int i) {
return sVect_[i];
}
with the header as follows:
class A{
public:
std::string getString(int i);
...
private:
vector<std::string> sVect_;
...
};
I've been trying to test the getString() function using googletest but an error keeps popping out:
error: invalid conversion from 'char* (*)(const char*, int)throw ()' to 'int'
error: initializing argument 1 of 'std::string A::getString(i)'
This was my test program:
TEST(ATest, getString){
A a;
EXPECT_EQ("c", a.getString(i));
}
I couldn't quite grasp the workaround of the vector string and how to call it in my test program without ever changing the production code. I even use the hack, adding #define statements, to access the private member but still couldn't do it.
How do my test actually looks like to successfully call that function?
Note: I'm on Linux and using gcc. Thank you in advance guys.
Perhaps the error message is misleading. Have you defined i globally somewhere else? To me it looks like in the local scope because it does not know what the value of the variable i is, it is misbehaving in an unexpected way
TEST(ATest, getString){
A a;
EXPECT_EQ("c", a.getString(i)); //here what is the 'i' and where is it defined
}

Possible Visual Studio 2015 C++ Compiler and IntelliSense Bugs

I encountered a compiler crash and intellisense false positives with Visual Studio 2015 using C++.
This crashes the compiler when written within a function block:
if();
This is the dialog that is shown when compiling (I am on a German version of Windows):
Even though the compiler crashes, I get error list output:
Error C2059 syntax error: ')'
Warning C4390 ';': empty controlled
statement found; is this the intent?
Error C1903 unable to recover from previous error(s); stopping compilation
This produces squiggles and error annotations in the vertical scrollbar in map mode, but no actual intellisense errors:
#include <vector>
struct S { std::vector<S> Children; };
int main(int argc, char* argv[]) {
S item;
item.Children.push_back(S());
// ^
// Error: no instance of overloaded function
// "std::vector<_Ty, _Alloc>::push_back [with _Ty=S, _Alloc=std::allocator<S>]"
// matches the argument list
// argument types are: (S)
// object type is: std::vector<S, std::allocator<S>>
S& back = item.Children.back();
// ^^^^
// Error: a reference of type "S &" (not const-qualified) cannot be
// initialized with a value of type "S"
return 0;
}
Are those bugs? Are they known? Can you reproduce them?
For the first case: the compiler shouldn't crash but just issue the diagnostic you show. So yes, that's a bug. Which doesn't occur in VS2013 btw. Submit a report for it here
For the second case: it is the same in VS2013 and is due to nesting a vector of S inside S. This and other cases make the error squiggles appear incorrectly, it is actually not that uncommon. But ideally it should not happen so you can submit a bug report for it as well, though it might be something which is going to be labelled 'wontfix' as the compiler team usually focusses on more urgent cases.

error: expected primary-expression before ')' token (C)

I am trying to call a function named characterSelection(SDL_Surface *screen, struct SelectionneNonSelectionne sel) which returns a void
This is the .h of the function I try to call:
struct SelectionneNonSelectionne;
void characterSelection(SDL_Surface *screen, struct SelectionneNonSelectionne);
void resetSelection(SDL_Surface *screen, struct SelectionneNonSelectionne);
On my main function, I try to call it like this:
characterSelection(screen, SelectionneNonSelectionne);
When I compile, I have the message:
error: expected primary-expression before ')' token
I made the includes. I suppose I miscall the second argument, my struct. But, I can't find why on the net.
Have you got any idea about what I did wrong?
You should create a variable of the type SelectionneNonSelectionne.
struct SelectionneNonSelectionne var;
After that pass that variable to the function like
characterSelection(screen, var);
The error is caused since you are passing the type name SelectionneNonSelectionne
A function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.
I seen this problem with the latest nightly build of Code::Blocks. When I switched back to the stable release of Code::Blocks, 20.03 at the time of this writing, the problem went away and my code compiled and ran without problems. I'm not sure what Code::Blocks is doing, but it is very annoying. I got this repeatedly on a C++ project for every NULL in my code, forcing me to use nullptr instead.

C++ goto (rather than continue) syntactic oddity

I have the following code:
do
{
doStuffP1();
if (test)
{ goto skip_increment;
}
dostuffP2();
skip_increment:
// 1; // Only works if I remove the comment at line start.
} while (loop);
Which doesn't compile (VC++ 2010) with this error:
file_system_helpers.cpp(109) : error C2143: syntax error : missing ';' before '}'
If I change it to:
skip_increment:
1;
It compiles (and works).
Is this really a limitation of C++ syntax?
I assume the "1;" was supposed to be missing from your first code snippet?
Look at this grammar here: http://www.lysator.liu.se/c/ANSI-C-grammar-y.html
This defines labels only as a "labeled-statement". That is, a block body can contain label: <statement> anywhere in its sequence of contents, but the statement after the label is not optional. So this would make skip_increment: } invalid.
(And, OK, you're using C++ and not C; but I doubt if making allowances for extra uses of goto was something anyone cared much about while defining the C++ language.)