Why wouldn't the following program compile? - c++

Why wouldn't the following code compile? Basically what is not right in the following code? I'm assuming that declaring the same variable twice without assigning any value would be the problem.
#include <iostream>
using namespace std; int foo() { return 1; }
int main() { int a; int a; cout << foo() << endl; return 0;}

remove one "int a;" declaration. Even if it was possible, there is no reason to do that.

Related

C++ does not recognize string as keyword

I tried the following code:
#include <iostream>
using namespace std;
int main()
{
char string[4]='xyz';
return 0;
}
Since string is a keyword the compiler should give error but it runs fine. Can anyone explain why it compiles successfully.
string is not a keyword.
It's the name of a type declared in the standard library.
When you give it a name, you're doing something called shadowing. This is more clear in the following example:
{
int x = 0;
{
int x = 5;
std::cout << x << std::endl;
}
std::cout << x << std::endl;
}
What gets printed?
Well, 5 first then 0.
This is because the x in the second scope overrides the x from the first. It "shadows" the first declaration.
This works with typenames as well:
struct MyStruct {
int x;
};
...
{
...
int MyStruct = 10;
...
}
Here, MyStruct gets overridden within that scope.
That same thing happens in your example with std::string

Declare an object inside a C++ class [duplicate]

I'm beginning to learn C++. In the IDE codeblocks, this compiles:
#include <iostream>
using namespace std;
struct A {};
struct B {
A a;
}
void hi() {
cout << "hi" << endl;
}
int main() {
hi();
return 0;
}
But this doesn't:
struct B {
A a;
}
struct A {};
int main() {
hi();
return 0;
}
void hi() {
cout << "hi" << endl;
}
It gives me the errors:
error: 'A' does not name a type
error: 'hi' was not declared in this scope
Should class/function order matter in C++? I thought it doesn't. Please clarify the issue.
Yes, you must at least declare the class/function before you use/call it, even if the actual definition does not come until afterwards.
That is why you often declare the classes/functions in header files, then #include them at the top of your cpp file. Then you can use the classes/functions in any order, since they have already been effectively declared.
Note in your case you could have done this. (working example)
void hi(); // This function is now declared
struct A; // This type is now declared
struct B {
A* a; // we can now have a pointer to it
};
int main() {
hi();
return 0;
}
void hi() { // Even though the definition is afterwards
cout << "hi" << endl;
}
struct A {}; // now A has a definition

I compiled this seemingly incorrect code, but I don’t understand why

I am learning C++ on a linux machine. I just tried “int i();” to declare a function but I forgot to define it. But to my surprise, this code can be compiled and output 1. I feel very confused. I tried “int I{};”, it still compiled with no errors. Please help to explain. Thanks in advance.
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
g++ test1.cpp
./a.out
Output is: 0
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
g++ test2.cpp
./a.out
Output is : 1
In your first example, you define a variable named i, and value-initialise it, which for int means zero-initialisation.
int i{}; // defines i, initialised to zero
In your second example, you declare a function named i, which takes no parameters, and return int:
int i(); // declares a function
When you print this:
std::cout << i << std::endl;
i first get converted to bool (i decays to a function non-nullptr pointer, then it becomes true), and then printed as an integer, that's why you get 1. The compiler can make this conversion without the definition of i (as the result is always true), that's why you got no linker error.
If your intent was to call this function, and print the result, you'll need to use i():
std::cout << i() << std::endl;
This, of course, needs i's definition.
In your code:
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
You are not actually declaring a function without defining it. The line of code int i{}; within the main() function here is a variable of type int named i and you are using a brace initializer list to initialize the variable i with out any values and in most cases could be 0 but can vary by compiler.
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
In this situation it is basically the same thing. You are within main() and by the rules of the language "you can not declare-define a function within a function", so this results in a declaration - definition of a variable. The only difference here is you are not using a brace initializer list here you are using it's ctor constructor called value initialization. Again you are not passing any values to it and in your case it's assigning an arbitrary value of 1.
Now if your code looked like this:
#include <iostream>
int i();
int main() {
std::cout << i() << '\n';
return 0;
}
This would fail to compile because the function i is declared but not defined. However if you did this:
#include <iostream>
// The text in quotes is not meant to be a string literal. It
// is the message of the text that represents any integer X.
int i() { return /*"some int value"*/ 1; }
int main() {
std::cout << i() << '\n';
return 0;
}
This would compile and run perfectly fine because the function i is both declared and defined.

Global Array in C++

Can anybody tell me what is wrong in the following code when I initialize a global array and want to print its value outside main() function
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
cout << global_array[2];
int main()
{
cout << "Hello World!" ;
}
The error keep popping is
error: 'cout' does not name a type|
The statement cout << global_array[2]; is not a declaration (it is an expression). Only declarations are allowed outside of functions.
So, if you want to print anything outside of main function, you can only do so by having the expression within another function.
I think the problem is that the code you have that does the printing is outside of any function. Statements in C++ need to be inside a function. For example:
#include <iostream>
using namespace std;
void hello();
int global_array[5] = {10,20,30,40,50};
void hello()
{
cout << global_array[2];
}
int main()
{
hello();
cout << "Hello World!" ;
}
Before asking a question, you can search: ‘cout’ does not name a type
Thanks you.
if you want to call it from outside the main it should be in a function something like this
#include <iostream>
using namespace std;
int global_array[5] = {10,20,30,40,50};
int pre()
{
cout << global_array[2];
return 0;
}
int x = pre();
int main()
{
cout<<"Hello World";
return 0;
}
as i mentioned it on comment it can be done via c++ classes.
#include <iostream>
int global_array[5] = { 10,20,30,40,50 };
struct foo
{
foo()
{
std::cout << global_array[2] << std::endl;
}
};
foo f;
int main()
{
}

Redeclaring a function inside a function

I stumbled across a strange c++ snippet. I consider this as bad code. Why would someone repeat the function declaration inside a function? It even compiles when changing the type signature to unsigned int sum(int, int) producing the expected result 4294967294j. Why does this even compile?
#include <iostream>
#include <typeinfo>
using namespace std;
int sum(int a, int b){
return a + b;
}
int main()
{
int sum(int, int); // redeclaring sum???
int a = -1;
auto result = sum(a, a);
cout << result << typeid(result).name() << endl;
}
Edit: It compiles for me... but is it valid C++ code? If not why does the compiler (mingw 4.8.1) allow it?
Sometimes there is a sense to redeclare a function inside a block scope. For example if you want to set a default argument. Consider the following code
#include <typeinfo>
using namespace std;
int sum(int a, int b){
return a + b;
}
int main()
{
int sum(int, int = -1 ); // redeclaring sum???
int a = -1;
auto result = sum(a, a);
cout << result << typeid(result).name() << endl;
result = sum(a);
cout << result << typeid(result).name() << endl;
}
Another case is when you want to call a concrete function from a set of overloaded functions. Consider the following example
#include <iostream>
void g( int ) { std::cout << "g( int )" << std::endl; }
void g( short ) { std::cout << "g( short )" << std::endl; }
int main()
{
char c = 'c';
g( c );
{
void g( short );
g( c );
}
}
If that's the actual code, there's no reason to do it.
If the function sum is defined somewhere else though, the declaration inside main makes it accessible only inside main. You can't use it anywhere else in that translation unit (unless of course you declare it). So it's a sort of limiting visibility to where it's needed, but, granted, it's not very readable.
Regarding changing the return type - that's illegal. You're not seeing any issues with unsigned int, but if you try
char sum(int, int); // redeclaring sum???
you'll see there's a problem there.