declaration syntax error - c++

What's wrong with this one? The compiler says: Declaration syntax error.
Source File:
#include<iostream>
using namespace std;
int main(int argc, char **argv) {
void printBinary(const unsigned char val) {
//printBinary() func. outputs byte in binary
for(int i=7;i>=0;i--)
if(val & (1<<i)) //generates a single bit with offset position
std::cout<<"1";
else
std::cout<<"0"
}
return 0;
}///:~
Header file:
void printBinary(const unsigned char val);
///:~

You are trying to define one function inside another function. This is illegal. Why did you place the definition of printBinary into the body of main?
Aside from the lambda functions in C++11, C++ has no such feature as local functions. All functions "live" in namespace scope.
The only workaround for this rule is inline member function definitions for local classes, although it does not produce a local function either.

You can't define a function in another function's (in this case, main) body.
//EDIT: Unless, of course, it's lambda.

Related

Alternatives To Global Variables in C++

I need to set a variable in the main function and access it from a different function in the same file. I can not pass it to the function because it means changing the entire code structure, which is not an option. To avoid declaring a global variable I crated a namespace and I want to check if this is a good programming practice or is there a cleaner way to do it.
This is the code:
namespace mylocalnamespace{
int myglobalvar;
}
static void myFunc()
{
..... some code
operationX(mylocalnamespace::myglobalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalnamespace::myglobalvar = atoi(argv[0]);
..... some code
}
Alternatives To Global Variables in C++
In the example, function argument is a good alternative to avoid a global variable:
static void myFunc(int mylocalvar)
{
..... some code
operationX(mylocalvar);
..... some code
}
int main(int argc, char **argv)
{
..... some code
mylocalvar = atoi(argv[0]);
..... some code
myFunc(mylocalvar);
}
I can not pass it to the function
Oh well, then you have to use a global variable.
Since you apparently use it in a function with internal linkage, you could improve slightly by using global with internal linkage as well. This way the global won't leak to other translation units. A handy way to achieve that is an anonymous namespace:
namespace {
int myglobalvar;
void myFunc() {
// ...
To avoid declaring a global variable I crated a namespace
Global variables are still global variables even if not in the global namespace.

Cannot Compile .cpp File When Trying To Define Private Var

I am attempting to compile a .cpp file that includes a .h file and then implements the class outlined.
In String.h:
using namespace std;
class String
{
private:
int _length;
char *data;
int getCharArraySize(char arr[]);
In String.cpp:
#include "String.h"
using namespace std;
/*
* Private vars and methods
*/
int String::_length;
char String::*data;
int String::getCharArraySize(char arr[])
{
//method body
return 0;
}
When I attempt to compile with g++ I get this error:
% g++ String.cpp -c
String.cpp:14:17: error: ‘int String::_length’ is not a static data member of ‘class String’
int String::_length;
I am only having issues with String::_length. I was initially thinking that it was due to _length being private but all the other private methods/vars, compile just fine. I also need to leave this .h file as is so I cannot just make it public. Any help would be appreciated!
Well, it's exactly as the compiler says: _length is not a static member variable. Yet, you are treating it as one by providing it with its own definition. Simply do not do that. Only static member variables should be defined like that.
The same goes for data.
By the way, if you do ever have to define a char* variable, then this is wrong:
char String::*data;
and this is right:
char* String::data;
Lexical grammar production oddities (inherited from C) notwithstanding, the * is part of the type, not the name.

Trouble with using namespace and static methods

I am trying to write some namespaces statics methods and variables in order to have a set of functions i can use from anywhere in the code. This is what I have:
Header:
namespace CProfileIO
{
static void setAppDir(std::string appDir);
static int reloadProfiles();
static std::string directory;
static std::list<std::string> profilesList;
}
Source:
namespace CProfileIO
{
void setAppDir(std::string appDir)
{
directory = appDir;
}
int reloadProfiles()
{
// ...
}
} // namespace CProfileIO
Then somewhere in the code I have:
#include "CProfileIO.h"
int main(int argc, char * argv[])
{
string appDir = string(dirname(*argv));
CProfileIO::setAppDir(appDir);
.
.
.
}
When I try to compile, i get error at the line I am using the function:
... undefined reference to `CProfileIO::setAppDir(std::string)'
I cant figure out what is wrong. I would aprichiate all help!
You should not use static functions here, as they are visible only in the current translation unit. Thus, you declare a static function which you define (statically) in the cpp, then it won't be visible from other translation units.
You should simply not use the static keyword here, but declare variables (but not functions) as extern.
Also, I recommend to pass the string argument as const reference (void setAppDir(const std::string& appDir);)
That is because static methods are only visible in the current module, (source file). They are not linked.
Hence you other sourcefile doesn't find the function. That is supposed to happen if you use static. I don't know why you would declared naked functions as static, maybe you meant to put them into a class?

Function Overloading in Visual c++

I was writing a program of function overloading in Visual C++ 2010 .
Following is my code
// overload.cpp : Defines the entry point for the console application.
#include<Windows.h>
#include<iostream>
#include<conio.h>
using namespace std;
//abs is overloaded in 3 types
int abs(int i);
double abs(double d);
long abs(long f);
void main()
{
cout<<abs(-10)<<"\n";
cout<<abs(-11.0)<<"\n";
cout<<abs(-9L)<<"\n";
getch();
}
int abs(int i)
{
cout<<"using integer abs()\n";
return i>0? -i:i;
}
double abs(double d)
{
cout<<"using double abs()\n";
return d>0? -d:d;
}
long abs (long l)
{
cout<<"using long abs()\n";
return l>0?-l:l;
}
I am having problems in double abs and long abs function that
1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(22): error C2084: function 'double abs(double)' already has a body
1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(26): error C2084: function 'long abs(long)' already has a body
Why this problem is coming?
I have changed the compilation from c to c++
but recently I ran an other program for overloading,it worked.I don't know how? here is the code.
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<cstring>
using namespace std;
void stradd(char*s1,char*s2);
void stradd(char*s1,int i);
void main()
{
char str[80];
strcpy(str,"hello");
stradd(str,"there");
cout<<str<<"\n";
getch();
}
//concatenate a string with a "stringized "integer
void stradd(char*s1,int i)
{
char temp[80];
sprintf(temp,"%d",i);
strcat(s1,temp);
}
//concatenate 2 strings
void stradd(char*s1,char *s2)
{
strcat(s1,s2);
}
and output is hellothere
Your problem comes from a header in which abs is declared for some types such as double. You're not allowed to have to functions with exactly the same header (that is, same return type, same name, same list of parameters, same qualifiers such as const).
There are two ways of avoiding this:
Use the standard library: std::abs is good, you don't need to implement it yourself
Naming the method absoluteValue or myAbs or whatever you like, but not abs
A third way, namely removing using namespace std does not work according to your comment. This is because you include Windows.h. This itself includes a bunch of headers, probably including math.h. This gives a method called abs in the global namespace. Better don't include Windows.h and include cmath if you need to. Then, abs is only declared in namespace std, hence you can call it with std::abs and is different from abs.
When overload resolution cannot select one function as the unique best match, the call is ambiguous. An ambiguous call produces a compilation error.
In std there is already an abs() with the following signature:
int abs (int n);
So while you try to overload it with double and long it results in ambiguity for the compiler.
If you're a beginner learning about coding i suggest you to use function names not defined in libraries (at least the ones you have included).
stefan have already given the solution to it:
Remove using namespace std; and explicitly write std::cout
OR
Re name your function to absoluteValue or something else
OR
Use explicit namespaces in function declaration and calls. (Not tested, though it should work)
Put your function inside a class or namespace.
Maybe this would provide you with a little insight (From SO).
EDIT:
The second question's overloaded functions stradd() is not defined in any other library. That is why no Compilation Errors. The following function signature in your code will result an error: char * strcat ( char * destination, const char * source )
Your primary problem is that you use global namespace. Just declare your function in your own namespace and all name collisions will be gone.
Let me explain why you're getting those compile-time errors.
Somewhere in the headers you included there are double abs(double) and long abs(long) functions. Then you're creating functions with the same signatures by your own. So compiler just don't know what to use when you'll call one of them - there are 2 pairs of equal functions. So it refuses to compile that, and you're getting those errors.
So you have 2 choices - hope that every time you'll want to create a function you will choose an unique name, or just create a namespace and your function names should be unique only to another functions in your namespace.
And it's not about overloading - void func(int i) overloads void func(float f), but void func(int i) overrides void func(int i). You can override superclass member functions in subclasses, but you cannot override standalone functions like abs().
just change abs function name with another.
abs() is a keyword therefore it is showing errors.

VC++: non-global old-style function declarations?

In Visual Studio 2003 using pure C, old-style function
declarations do not show as global member
i.e. void func(blah) int blah;{...}
This shows as a global member in the members dropdown:
void func(int blah)
{
...
}
This compiles, but old-style does not appear in the global
members dropdown:
void func(blah)
int blah;
{
...
}
I am trying to use the new 'Calling Graph' functionality to
analyse code, but as most of our legacy code uses the
old-style function parameters, those functions are not
recognized are not shown as Global Members, and therefore do
not appear in the 'Calling Graph'.
Is there any way to let the "call graph" analysis process
old-style function declarations correctly?
Maybe you want to consider to just change the old style function signatures. There shouldn't be any issues with that.
EDIT:
For an automatic conversion of your source files from old style syntax to ANSI-C style, take a look at the cproto tool. Maybe that could save you some time if you decide to go that direction.
This is an excerpt from the docs:
-f n
Set the style of generated function prototypes where n is a
number from 0 to 3. For example,
consider the function definition
main (argc, argv)
int argc;
char *argv[];
{
}
If the value is 0, then no prototypes are generated. When set to
1, the output is:
int main(/*int argc, char *argv[]*/);
For a value of 2, the output has the form:
int main(int /*argc*/, char */*argv*/[]);
The default value is 3. It produces the full function prototype:
int main(int argc, char *argv[]);
I'm not sure but maybe the engine uses regexs to trace routine signatures and the old C style isn't implemented.