I am very very VERY new to coding with C++, but I have some experience with Python, and wanted to start to learn functions very early on because I know how much of a lifesaver they can be in the future, can anyone help me figure this out
here is my code
#include <iostream>
using namespace std;
int helloWorld()
{
cout << "Hello World!" << endl;
return 0;
}
int main()
{
int helloWorld;
return 0;
}
In this snippet:
int main()
{
// Uninitialized variable declaration, no function call
int helloWorld;
return 0;
}
You're just simply declaring an uninitialized integer variable, you are not calling the function anywhere.
You need to call it:
int main(void)
{
helloWorld(); // no need of 'int helloWorld()', 'void' is enough
return 0;
}
Related
I have come across to an interesting thing. In an interview I was asked to print "Hello World" to the console. But the main function must be:
int main(void)
{
return 0;
}
it must not be modified!
I tried to #define return printf("Hello World");
Worked with C++ and MinGW GCC.
Even if this is like no style ;)
class TEST{
public:
TEST(){
cout << "Hello World";
}
};
TEST test_obj; //Create an instnace to TEST Class
int main(){
return 0;
}
NeverToLow beat me to it.
This works in either C or C++ (and is, of course, horribly bad style in either language):
#include <stdio.h>
#define return puts("Hello World");
int main(void) {
return 0;
}
The semicolon in the macro definition is necessary. It causes the following 0; to be a statement expression, which does nothing. (Falling off the end of main does an implicit return 0; in C++, and in C starting with C99.)
the macro approach which consists in redefining return is nice but has some drawbacks since it's not strictly compliant with the c89 standard and generates some warnings:
> gcc -std=c89 -Wall test.c
test.c: In function 'main':
test.c:7:12: warning: statement with no effect [-Wunused-value]
return 0;
^
test.c:8:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
now we could derive from this method, redefining just main, and an unused function after that
#include "stdio.h"
#define main(x) main(x) { printf("Hello world\n"); return 0; } int foo()
int main(void)
{
return 0;
}
preprocessor output:
int main(void) { printf("Hello world\n"); return 0; } int foo()
{
return 0;
}
now the program compiles without warnings, with c89 standard, and doesn't redefine a keyword.
You can define a function before main and pass a constructor to print Hello World.
#include<bits/stdc++.h>
using namespace std;
class print{
print(){
cout << "Hello World";
}
};
print obj;
int main(){
return 0;
}
You can also use macro preprocessor (define macros).
#include<bits/stdc++.h>
using namespace std;
#define return printf("Hello World");
int main(){
return 0;
}
You can link it with a shared library and put a return printf("Hello World"); in DLLmain under Windows or compile with option -init,DLLMain under Linux.
You can move that functionality into initialization code. For instance, in C++ you can declare a static instance of a class, then print that message in the class constructor.
Or, you may include a library via #pragma and do that code in "loaded" event:
https://stackoverflow.com/a/9759936/1964969
You can simply do that by making a class. In this code we have made a constructor in our HelloWorld class and what that constructor will do is print Hello World so whenever we make an object of class HelloWorld. The compiler will check what is written in the class HelloWorld and when it will see that there is a constructor in that class, it will check what is written in that constructor. We have written the code that will print HelloWorld. So it will make that object to print Hello World becuase of our constructor. I hope this code and explanation will help you
#include <bits/stdc++.h>
using namespace std;
class HelloWorld
{
public:
HelloWorld()
{
cout << "Hello World" << endl;
}
};
HelloWorld obj;
int main()
{
return 0;
}
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()
{
}
I am developing a C++ tool that should run transparent to main program. That is: if user simply links the tool to his program the tool will be activated. For that I need to invoke two functions, function a(), before main() gets control and function b() after main() finishes.
I can easily do the first by declaring a global variable in my program and have it initialize by return code of a(). i.e
int v = a() ;
but I cannot find a way to call b() after main() finishes?
Does any one can think of a way to do this?
The tool runs on windows, but I'd rather not use any OS specific calls.
Thank you, George
Use RAII, with a and b called in constructor/destructor.
class MyObj {
MyObj()
{
a();
};
~MyObj()
{
b();
};
};
Then just have an instance of MyObj outside the scope of main()
MyObj obj;
main()
{
...
}
Some things to note.
This is bog-standard C++ and will work on any platform
You can use this without changing ANY existing source code, simply by having your instance of MyObj in a separate compilation unit.
While it will run before and after main(), any other objects constructed outside main will also run at this time. And you have little control of the order
of your object's construction/destruction, among those others.
SOLUTION IN C:
have a look at atexit:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void bye(void)
{
printf("That was all, folks\n");
}
int main(void)
{
long a;
int i;
a = sysconf(_SC_ATEXIT_MAX);
printf("ATEXIT_MAX = %ld\n", a);
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
http://linux.die.net/man/3/atexit
this still implies however that you have access to your main and you can add the atexit call. If you have no access to the main and you cannot add this function call I do not think there is any option.
EDIT:
SOLUTION IN C++:
as sudgested there is a c++ equivalent from std. I simply paste in here an example which i copied from the link available just below the code:
#include <iostream>
#include <cstdlib>
void atexit_handler_1()
{
std::cout << "at exit #1\n";
}
void atexit_handler_2()
{
std::cout << "at exit #2\n";
}
int main()
{
const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);
if ((result_1 != 0) or (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
std::cout << "returning from main\n";
return EXIT_SUCCESS;
}
http://en.cppreference.com/w/cpp/utility/program/atexit
Isn't any global variable constructed before main and destructed afterward? I made a test struct whose constructor is called before main and the destructor afterward.
#include <iostream>
struct Test
{
Test() { std::cout << "Before main..." << std::endl; }
~Test() { std::cout << "After main..." << std::endl; }
};
Test test;
int main()
{
std::cout << "Returning now..." << std::endl;
return 0;
}
If you're happy to stick with a single compiler and non-standard C/C++, then GCC's __attribute__((constructor)) and __attribute__((destructor)) might be of use:
#include <stdio.h>
void __attribute__((constructor)) ctor()
{
printf("Before main()\n");
}
void __attribute__((destructor)) dtor()
{
printf("After main()\n");
}
int main()
{
printf("main()\n");
return 0;
}
Result:
Before main()
main()
After main()
Alternatively to the destructor, you can use atexit() in a similar manner - in C++, you do not need to have access to main() to register atexit there. You can do that as well it in your a() - for example:
void b(void) {
std::cout << "Exiting.\n";
}
int a(void) {
std::cout << "Starting.\n";
atexit(b);
return 0;
}
// global in your module
int i = a();
That being said, I'd also prefer the global C++ class object, which will call the b() stuff in its destructor.
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.
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.