Strange character added while compilation, leads to an error - c++

When compiling a project with Visual Studio Express 2013, I get this error
....\WDL\IPlug\IPlugVST3.cpp(199): error C2065: 'Lp' : undeclared identifier [D:\wdl-ol\IPlugExamples\MyFirstPlugin\MyFirstPlugin-vst3.vcxproj]
The strange thing is that the file IPlugVST3.cpp doesn't contain Lp but only p:
switch (p->Type())
{
case IParam::kTypeDouble:
case IParam::kTypeInt:
{
Parameter* param = new RangeParameter( STR16(p->GetNameForHost()), // <---- this line
i,
STR16(p->GetLabelForHost()),
p->GetMin(),
p->GetMax(),
p->GetDefault(),
0, // continuous
flags,
unitID);
param->setPrecision (p->GetPrecision());
parameters.addParameter(param);
Why does the C++ compiler understands it a Lp instead of p ?
Note: I checked if there are no hidden unicode characters (does this exist?) but no...

STR16 is most likely a macro which expects a string literal as an argument, e.g.
#define STR16(s) L##s
or something similar. It you pass a variable instead of a string literal then you will get something like the problem you are observing.

Related

Pseudo-code given in class that I'm trying to comprehend with the associated lab assignment in c++

So I've tried to figure out what exactly the professor was writing on the board and how it answers the lab assignment we are to do.
This is the lab assignment:
Create a Hash Table and Hash map that holds all of the WORDS in the (given below) Declaration of Independence.
Handle collisions using the chain method. (Note we will not be modifying this table nor doing deletions!)
Programmatically answer the following questions:
What is the size of your hash table?
What is the longest collision (ie. Chain)
What is the most frequently used word and how did you determine it?
Create a (second) Hash Table that holds all of the LETTERS in the Declaration of Independence.
What is the size of your hash table
What letter has the longest collision?
And this is the pseudo-code with some modifications that I did to fix some errors:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
class Translate
{
string word;
public:
int trans(string word);
w = word.charAT(0); //gives a letter
return #num;
};
class HashTable
{
int size();
int collision();
int length();
char fword();
public:
Translate t;
list<string> hashTable[29];
bool insert(string word)
{
hashTable[t.trans(word)].push_back(word);
return true;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
open file f("hash.txt");
//h.insert(word)
while (!f.eof())
{
h.insert(f.word());
}
cout << h.size;
cout << h.collision.length;
cout << h.fword;
return 0;
}
The errors that I have are:
Error 15 error C1903: unable to recover from previous error(s); stopping compilation
Error 5 error C2014: preprocessor command must start as first nonwhite space
Error 4 error C2059: syntax error : 'return'
Error 13 error C2065: 'f' : undeclared identifier
Error 10 error C2065: 'file' : undeclared identifier
Error 8 error C2065: 'open' : undeclared identifier
Error 6 error C2143: syntax error : missing ';' before '}'
Error 1 error C2143: syntax error : missing ';' before '='
Error 11 error C2146: syntax error : missing ';' before identifier 'f'
Error 9 error C2146: syntax error : missing ';' before identifier 'file'
Error 14 error C2228: left of '.eof' must have class/struct/union
Error 3 error C2238: unexpected token(s) preceding ';'
Error 7 error C2238: unexpected token(s) preceding ';'
Error 12 error C3861: 'f': identifier not found
Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error 19 IntelliSense: '#' not expected here
Error 17 IntelliSense: class "std::basic_string, std::allocator>" has no member "charAT"
Error 21 IntelliSense: expected a ';'
Error 18 IntelliSense: expected a declaration
Error 22 IntelliSense: identifier "f" is undefined
Error 20 IntelliSense: identifier "open" is undefined
Error 16 IntelliSense: this declaration has no storage class or type specifier
I've never used .c_str and I'm still pretty new to C++ so my knowledge is limited. I can tell that there are places that need an identifier but I think there is a better way to create a "open file". My previous knowledge is C#, HTML, and some Python in which C++ is giving me some difficulty in learning and understanding. Any help and/or insight would be greatly appreciated!
Code is too mangled to understand. However, I'm trying my best to help with the little knowledge of mine on C++ and hash.
Proposed Code Modification
Program entry point : instead of int _tmain(int, _TCHAR*), use int main().This should guarantee you the ability to test things out should you migrate to non-windows compiler.
Source : Unicode _tmain vs main
I would like to help with the remainder, however, the code posted is way too unintelligible. Would be kind if the algorithm is posted for reference.
There are a few things you should change:
Assuming trans() is supposed to be a function definition, not a declaration, and the lines following it are supposed to be the body:
Unless you specifically want to copy the passed string, you should use const string& instead of string.
It should have braces.
w is a char.
std::string defines operator[], so it can be indexed like an array.
I'm not sure what #num is (I assume it's from Python, but I'm not familiar with that), so I'm not sure how you intend to calculate the return value.
[I will thus assume that you want to return w, but as an int instead of a char. If this is the case, it would be simpler to just return word[0];.]
There are a few issues with HashTable's members.
Member functions size(), collision(), length(), and fword() are private. This doesn't appear to be intentional.
Member variables t and hashTable are public, when you likely wanted them to be private. Again, this doesn't appear to be intentional.
The functions aren't actually defined anywhere, unless you didn't show their definitions. This will cause a linking error when you call them.
While this doesn't need to be changed, there's no reason for HashTable::insert() to actually return a value, if it's hard-coded to always return true. Also, as mentioned in 1.1 above, the parameter should probably be const string&.
_tmain() and _TCHAR are a Microsoft extensions, which is available on Visual Studio and some (but not all) compilers aiming for compatibility with it (such as C++Builder). If you want your code to be platform-independent, you likely want main(). [Note that this doesn't need to be changed. If you're only compiling with Visual Studio, you can leave it as is. If you want platform independence, you can easily define _tmain and _TCHAR yourself.]
Opening a file:
Neither open nor file are keywords in C++, nor are they types (although FILE is a C type, it doesn't appear to be what you want). You appear to want std::ifstream.
You shouldn't use !f.eof() as a condition in a while loop, because eofbit won't be set until after reading fails.
fstream has no member function word(). However, the extraction operator, operator>>() will read a single word at a time, if given a parameter that can accept one.
HashTable::size(), HashTable::collision(), HashTable::length(), and HashTable::fword() are functions. To call them, you use operator(). If you just use a function's name directly, you don't call it, but instead refer to it (this can be used to create a function pointer or function reference).
int has no member function length(). Therefore, you cannot call h.collision().length(). In C++, if you chain function calls like that, each function in the chain is treated as if it were a member function of the directly preceding type, not the leftmost type; this means that for every function after the first, the return type of the preceding function is used. (In this case, h.collision() returns an int, so .length() attempts to call member function int::length(). int isn't a class type, and thus doesn't have any member functions.)
So, considering these, your code can be modified as follows:
// Assuming your stdafx.h contains "#include <string>" and "#include <tchar.h>".
// If it doesn't, either put them there, or #include them here.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <list>
// #4: Defining _tmain and _TCHAR
#ifndef _tmain
#define _tmain main
typedef char _TCHAR;
#endif
using namespace std;
class Translate
{
string word;
public:
// #1: Fixing trans().
int trans(const string& word)
{
char w = word[0]; // First letter of word.
return w; // Will be promoted to int.
}
};
class HashTable
{
// #2: Making member functions public, and member variables private.
Translate t;
list<string> hashTable[29];
public:
int size();
int collision();
int length();
char fword();
// #3: Making word a const reference. Changing return type to void.
void insert(const string& word)
{
hashTable[t.trans(word)].push_back(word);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
HashTable h;
// #5.1: Opening the file.
ifstream f("hash.txt");
//h.insert(word)
// #5.2 & 5.3: Reading a word.
std::string word;
while (f >> word)
{
h.insert(word);
}
// #6: Calling functions.
cout << h.size();
cout << h.collision(); // #7: Assuming you wanted to output both h.collision() and
cout << h.length(); // h.length(), I put them on separate lines.
// If you actually DID want h.collision().length(), then
// h.collision() should return a type (or reference to a type)
// with member function length(), or be an instance
// (or reference to an instance) of a class with member function
// length() (instead of being a function).
cout << h.fword();
return 0;
}
You still need to provide bodies for HashTable's member functions, apart from insert(), as well as make any other modifications you desire. You might also want to remove member word from Translate, if it doesn't actually need to store a string.

None of the 3 overloads could convert all the argument types (in MFC / C++ project)

I have copied some code from another project which I downloaded (and which compiled fine) and get the compiler error message when compiling the same code ( a file called player.cpp) in my own project:
Error 1 error C2665: 'MATExceptions::MATExceptions' : none of the 3 overloads could convert all the argument types c:\users\daniel\documents\visual studio 2012\projects\mytest1\mytest1\player.cpp 137 1 Test1
The error occurs on this line in player.cpp:
EXCEP(DirectSoundErr::GetErrDesc(hres), _T("Player::CreateDS DirectSoundCreate"));
Here is the definition of EXCEP and GetErrDesc:
#define EXCEP(/*const wchar_t * */ desc, /*const wchar_t * */ from) throw( MATExceptions(__LINE__, _T(__FILE__), 0, from, desc) );
CComBSTR DirectSoundErr::GetErrDesc(HRESULT hres)
{
switch(hres)
{
case DSERR_ALLOCATED :
return _T("The request failed because resources, such as a
priority level, were already in use by another caller.");
...
default : return _T("Unknown error");
}
}
I don't know what is different (as I have not changed the source file player.cpp). Could it be due to different compiler settings in my project compared to the original (how would I check this)?
I changed the EXCEP definition to the following:
#define EXCEP(desc, from) throw(MATExceptions(__LINE__, (wchar_t *)(__FILE__), 0, (wchar_t *)from, (wchar_t *)desc));
...and changed the call from:
EXCEP(DirectSoundErr::GetErrDesc(hres), _T("Player::CreateDS DirectSoundCreate"));
to:
EXCEP(DirectSoundErr::GetErrDesc(hres), "Player::CreateDS DirectSoundCreate");
Is that acceptable?
The original "new" can be killed by defining these in project (since Visual Studio 2015 I guess):
__PLACEMENT_NEW_INLINE
__PLACEMENT_VEC_NEW_INLINE
But once they are gone, they are gone. Now you need to make sure to include the project-specific header file which redefines them.

why type casting on non-pointer struct give syntax error

I am using Visual C++ express 2008 try to compile code similar to below:
no problem
{
...
AVRational test = {1, 1000};
...
}
but has problem when it is as below:
{
...
AVRational test = (AVRational){1, 1000};
...
}
gave errors:
1>..\..\..\projects\test\xyz.cpp(1139) : error C2059: syntax error : '{'
1>..\..\..\projects\test\xyz.cpp(1139) : error C2143: syntax error : missing ';' before '{'
1>..\..\..\projects\test\xyz.cpp(1139) : error C2143: syntax error : missing ';' before '}'
where AVRational (ffmpeg.org library) is defined as:
typedef struct AVRational{
int num; ///< numerator
int den; ///< denominator
} AVRational;
FFmpeg come with some pre-define value such as
#define AV_TIME_BASE_Q (AVRational){1, AV_TIME_BASE}
which is used as below
av_rescale_q(seek_target, AV_TIME_BASE_Q, pFormatCtx->streams[stream_index]->time_base);
will failed to compile on Visual C++ express 2008
It seem like the same code will be compiled with no error/warning on gcc compiler. Why I get this error on VC++? Is it a C/C++ standard way to do casting on struct value? Anyway I can avoid this error while still able to use the defined AV_TIME_BASE_Q?
Use av_get_time_base_q() instead of AV_TIME_BASE_Q for C++ or VS.
This was fixed in a patch
VC++ 2013 does not allow compound literals in C++ but it allows them in C. Options:
Rename your program with a .c suffix
Switch on the /TC flag for the program that does not compile.
The other alternative if you wish to keep to C++ is to change the declaration of AV_TIME_BASE_Q in the header file
static const AVRational AV_TIME_BASE_Q = {1, AV_TIME_BASE};
Then it will be using the constant instead of the compound literal.
For compound-literals errors in C++
wrong:
this->buffer.enqueue((tone_t) { duration, frequency });
correct:
tone_t tone = { duration, frequency };
this->buffer.enqueue(tone);

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.)

Strange behaviour with templates and #defines

I have the following definitions:
template<typename T1, typename T2>
class Test2
{
public:
static int hello() { return 0; }
};
template<typename T>
class Test1
{
public:
static int hello() { return 0; }
};
#define VERIFY_R(call) { if (call == 0) printf("yea");}
With these, I try to compile the following:
VERIFY_R( Test1<int>::hello() );
this compiles fine
VERIFY_R( (Test2<int,int>::hello()) );
this also compiles fine, notice the parentheses around the call.
VERIFY_R( Test2<int,int>::hello() );
This, without the parentheses produces a warning and several syntax errors:
warning C4002: too many actual parameters for macro 'VERIFY_R'
error C2143: syntax error : missing ',' before ')'
error C2059: syntax error : ')'
error C2143: syntax error : missing ';' before '}'
error C2143: syntax error : missing ';' before '}'
error C2143: syntax error : missing ';' before '}'
fatal error C1004: unexpected end-of-file found
What's going on here?
This happens with VS2008 SP1.
The comma inside a macro can be ambiguous: an extra set of parentheses (your second example) is one way of disambiguating. Consider a macro
#define VERIFY(A, B) { if ( (A) && (B) ) printf("hi"); }
then you could write VERIFY( foo<bar, x> y ).
Another way of disambiguating is with
typedef Test1<int,int> TestII;
VERIFY_R( TestII::hello() );
The preprocessor is a dumb text replacement tool that knows nothing about C++. It interprets
VERIFY_R( Test1<int,int>::hello() );
as
VERIFY_R( (Test1<int), (int>::hello()) );
which calls VERIFY_R with too many parameters. As you noted, additional parentheses fix this:
VERIFY_R( (Test1<int,int>::hello()) );
The question remains, however, why you need the preprocessor anyway. The macro you used in your question could just as well be an inline function. If you real code doesn't do anything requiring the preprocessor, try to get rid of macros. They just cause pain.
The comma in <int, int> is treated as an argument separator for the macro, rather than for the template. The compiler therefore thinks you're calling VERIFY_R with two arguments (Test1<int and int>::hello()), when it requires only one. You need to use variadic macros to expand everything supplied to the macro:
#define VERIFY_R(...) { if ((__VA_ARGS__) == 0) printf("yea");}
It is generally a good idea to wrap macro arguments in parentheses, as well, to prevent other kinds of weird substitution errors.
The preprocessor doesn't know that < and > are supposed to be brackets, so it interprets the expression as two macro arguments, Test1<int and int>::hello(), separated by the ,. As you say, it can be fixed by surrounding the entire expression with parentheses, which the preprocessor does recognise as brackets.
I'm not sure if this is an error in your reporting here or the actual problem, but your last VERIFY_R is still referencing Test1, rather than Test2.