"nice" keyword in c++? - c++

So I was doing some simple C++ exercises and I noticed an interesting feat. Boiled down to bare metal one could try out compiling the following code:
class nice
{
public:
nice() {}
};
int main()
{
nice n;
return 0;
};
The result is a compilation error that goes something like this:
<file>.cpp: In function ‘int main()’:
<file>.cpp:11: error: expected `;' before ‘n’
<file>.cpp:11: warning: statement is a reference, not call, to function ‘nice’
<file>.cpp:11: warning: statement has no effect
And this was using regular g++ on Max OS X, some of my friends have tried in on Ubuntu as well, yielding the same result.
The feat seems to lie in the word "nice", because refactoring it allows us to compile. Now, I can't find the "nice" in the keyword listings for C++ or C, so I was wondering if anyone here had an idea?
Also, putting
class nice n;
instead of
nice n;
fixes the problem.
P.S. I'm a relative C++ newbie, and come from the ActionScript/.NET/Java/Python world.
Update:
Right, my bad, I also had an
#include <iostream>
at the top, which seems to be the root of the problem, because without it everything works just fine.

Maybe the problem is somehow caused by function nice in libc. It is similar to trying to name your class printf.

using namespace std, by any chance?
Edit:
The standard says that standard headers define all their symbols in namespace std (see 17.4.1.2.4).
A footnote, however, also says that the <.h> variants dump their names into the global namespace - but of course no one should be using these ;)

It is a namespace problem but not with namespace std. The header <iostream> is pulling in <unistd.h>
If you try
class nice
{
public:
nice() {};
};
int main(int argc, char *argv[])
{
nice n;
return 0;
}
there is no problem.
Simply add
#include <unistd.h>
and you will get the "expected ‘;’ before ‘n’" error. Namespace std does not enter the picture.
So the solution is the same as before - put class nice in its own namespace and it will not clash with the global ::nice().

Try this version:
#include <iostream>
namespace test
{
class nice
{
public:
nice() {}
};
};
using namespace std;
int main()
{
test::nice n;
cout << "well I think this works." << endl;
return 0;
}
In this case I've defined my own namespace test. Doing so, I can use whatever class names I like, including functions already defined like printf. The only things I can't re-use are reserved words like int or namespace.
Note: if you say:
using namespace test;
As well and refer to nice alone, you'll get this error:
nice.cpp: In function ‘int main()’:
nice.cpp:18: error: reference to ‘nice’ is ambiguous
/usr/include/unistd.h:593: error: candidates are: int nice(int)
nice.cpp:7: error: class test::nice
Which I think explains nicely what's going on - nice now exists in two namespaces and the compiler can't work out which one you mean.

It works fine for me. Did you try the exact code you posted?

extern "C"
{
#include <unistd.h>
}

Related

c++ namespace class conflict

i have named this as next.h and included in main.cpp snippet
i have created two libraries one for the main function and the other just for having classes
i wanted to practise for OOPS so i suddenly thought of using namespaces to know their full potential but i am getting confused between why it isnt working as intended
#include<bits/stdc++.h>
namespace custom
{
class aries
{
public:
int data;
};
}
namespace custom2
{
class aries
{
public:
double data1;
};
}
#include<bits/stdc++.h>
#include "next.h"
using namespace std;
using namespace custom;
using namespace custom2;
int main()
{
custom2::aries a;
a.data1=5.000;
cout<<a.data1;
return 0;
}
The output for the following program is as follows:
5
...Program finished with exit code 0
Press ENTER to exit console.
My question is it should have been 5.000 but why it is int type and not a double type ?
Okay, just summing up the comments:
don't use the #include <bits/stdc++.h>. Instead, just include every header you need to use in your code separately. Reason: bad code readability and not every compiler supports this directive. More: Why should I not #include <bits/stdc++.h>?
also don't use the using namespace *name* command. For clarity: you can use namespaces, just don't use using, use *namespace name*:: instead, like std::cout. Reason: bad code readability, also you can mess up with names (like when you have function_name function and the namespace also has a function with the same name, then the compiler will not know which to use (or you get an error).
answer to your question: std::cout omits zeros while printing numbers so 5.00 will be just 5, but 5.278 will be 5.278.

Why do I get an error in this code when using "using namespace std;" and "bits/stdc++.h"?

Actually this code works fine in "DEV C++", but when I put it into my "Hacker-Rank" panel it gives this error "reference to function is ambiguous", although all the online compilers are giving errors...
I don't think here function overloading is somewhere interrupting, because this error mostly comes in function overloading.
#include <bits/stdc++.h>
#include <cstdio>
#include<iostream>
using namespace std;
int function(int n);
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(n<=0){
return(0);
}
else{
function(n);
}
}
int function(int n)
{
if (n<=9)
{
cout<<"experiment";
}
else{
cout<<"Greater than 9";
}
return 0;
}
The error with clang is:
<source>:20:9: error: reference to 'function' is ambiguous
function(n);
^
<source>:8:5: note: candidate found by name lookup is 'function'
int function(int n);
^
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/11.0.0/../../../../include/c++/11.0.0/bits/std_function.h:111:11: note: candidate found by name lookup is 'std::function'
class function;
^
// ... and more ....
For starters this else code block
else{
function(n);
}
returns nothing.
Though it is allowed but confuses readers of the program because they expect that if there is an explicit return statement in the if sub-statement then a similar return statement should be in the else sub-statement.
It seems the name function declared in the global name space conflicts with the standard name std::function due to the using directive.
using namespace std;
Write
else{
return ::function(n);
}
The problem is caused by #include <bits/stdc++.h> combined with the directive using namespace std.
<bits/stdc++.h> includes most (all, depending on the age of the version you have with your compiler) headers related to the C++ standard library.
One of the headers included by <bits/stdc++.h> (since C++11) is <functional>, which declares a templated class std::function. std::function has a templated constructor that can accept a single argument of any type.
In your main(), anything declared (visible to the compiler) named function is a candidate for being used by the statement function(n). The directive using namespace std tells the compiler to consider names within std as candidates. According to rules of the language, both your declared function() and std::function are equally good matches for the name function.
The real fix has two parts. The first is to avoid using headers like <bits/stdc++.h> and, instead, only include standard headers that are actually needed by your program.
The second part is to avoid using the directive using namespace std excessively, or even at all. It can cause names (of types, functions, variables, etc) within standard headers to accidentally match names in your code.
If you do a search, you will find plenty of explanations of why to avoid both <bits/stdc++.h> and to avoid using namespace std (or other using directives). Both have their uses, but both introduce hard-to-avoid gotchas (such as you have experienced).
Vlad has shown that working around the problems caused by using namespace std; can solve your problem. That is a good answer.
Funnily, you can also fix your problem by not applying the antipattern #include <bits/stdc++.h>. Even without Vlads proposed improvement.
#include <limits>
#include <cstdio>
#include<iostream>
using namespace std;
int function(int n);
int main()
{
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(n<=0){
return(0);
}
else{
function(n);
}
}
int function(int n)
{
if (n<=9)
{
cout<<"experiment";
}
else{
cout<<"Greater than 9";
}
return 0;
}
More info on why I dare to describe that as "antipattern" is here:
Why should I not #include <bits/stdc++.h>?

'list' was not declared in this scope

I am new to c++, and I am trying to get a basic program to initialize a list of short unsigned integers. I am compiling and running using scygwin and g++.
Below is the code in the .cpp file:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <typeinfo>
using namespace std;
int main (int argc, char* argv[]) {
list<int> events;
return 0;
}
which I run by typing the following command into cygwin terminal:
$ g++ -o test.out test.cpp
However, I get the following compilation errors:
test.cpp: In function ‘int main(int, char**)’: test.cpp:16:1: error:
‘list’ was not declared in this scope list events;
^
test.cpp:16:6: error: expected primary-expression before ‘int’
list events;
^
I am confused about why list is not in the scope, since I am using namespace std? I found a similar question asked about this on a c++ forum, but my problem would be resolved with that. Anyone know what the problem is here?
-Paul
using namespace std; doesn't add any functionality to your code. It just means you don't have to type std:: when referencing things in the std namespace, like std::list.
To actually include the code base for std::list into your program, you need to add:
#include <list>
When in doubt about this kind of thing, doing a google search for cpp reference list will turn up a page like this where you can see: Defined in header <list> at the top.
Here's another question about using namespace std; that may prove useful and why you shouldn't use it. I'll add a little bit to perhaps explain namespaces.
It is common in C++ programs to organize functions into classes and namespaces. Imagine you wrote your own list class to handle certain scenarios. In order to prevent naming conflicts you would put it in a different namespace than std.
namespace MyApp {
class list;
void sort(list&);
}
For the majority of a large code base you might still prefer to use std::list but you need MyApp::list for some things. Using namespaces you can cluster your code and prevent naming conflicts for similar functionality.
Summary
using namespace std; makes it so that if you reference a function or class not in the global namespace it looks for it in the std namespace.
#include <list> actually inserts prototypes (information about how to access the code) in your source file during the preprocessor stage.

"Not declared in scope" C++ issue

I'm writing a simple class in C++ for a class (school, not code). I have a little C++ experience, but it's been a while so I'm relearning whatever I forgot and learning a lot of new syntax (I have much more experience in Java). Here is the code:
#include <iostream>
#include <string>
using namespace std;
class Project112
{
private:
string romanNumeral;
int decimalForm;
public:
Project112()
{
romanNumeral = "";
decimalForm = 0;
}
int getDecimal()
{
return decimalForm;
}
};
and here is the driver:
include cstdlib
include <iostream>
using namespace std;
int main()
{
Project112 x;
int value2 = x.getDecimal();
return 0;
}
This is part of a larger program, but I've simplified it down to this because this is the where the problem lies. Every time I try to run the program, I get the following errors:
main.cpp:10: error: 'Project112' was not declared in this scope
main.cpp:10: error: expected `;' before 'x'
main.cpp:14: error: 'x' was not declared in this scope
Can someone please explain the problem? Thanks in advance.
#include "Project112.h"
Add that above main. You forgot to include the header file. And:
using namespace std;
Don't do that in a header file. That imports the everything from the std namespace into the global namespace of any file which includes your header. Just fully qualify the type in a header, i.e., std::string, and I would avoid that in implementation files as well in a large project (though something like using std::string is ok IMO in an implementation file).

Explain the error: ISO C++ forbids declaration of `Personlist' with no type

I have a class which is going to handle an array of objects of another class I've created earlier (which works fine). The problem appears when I try to create an object of my List-class.
This is the header of the list-class:
#ifndef personlistH
#define personlistH
#include "Person.h"
#include <iomanip>
#include <iostream>
#define SIZE 10
namespace std {
class PersonList {
private:
Person persons[SIZE];
int arrnum;
string filename;
public:
Personlist();
};
}
#endif
This is the main function:
#include <iostream>
#include "PersonList.h"
using namespace std;
int main() {
PersonList personlist;
return 0;
}
The error my compiler is giving me is the following:
error: "27 \PersonList.h ISO C++ forbids declaration of `Personlist'
with no type"
I've searched for answers but as I'm quite new to C++ it's been a bit confusing and I haven't found any fitting yet. It would be great if you could explain this error for me.
You have the wrong capitalisation on your constructor declaration. You have Personlist(); but need PersonList();. Because what you have isn't equal to the class name it is considered a function rather than a constructor, and a function needs a return type.
Do not add your own types to the standard namespace(std), instead create your own namespace and define your class inside it.
//PersonList.h
namespace PersonNamespace
{
class PersonList
{
//members here
};
}
//Main.cpp
using namespace PersonNamespace;
The actual error is that you made a typo in Personlist instead of PersonList
The error is because you got the capitalisation wrong when you declared the constructor; it should be PersonList() not Personlist().
Also, you should never declare your own classes in the std namespace; that's reserved for the standard library. You shoud make up your own namespace name, and put your things in that.