How to print Hello World in an empty main function - c++

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;
}

Related

Code doesn't display anything when it should display "Hello World!"

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;
}

C++ Segmentation Fault when Assigning Class Member Variable

I have a function "testfunc()" within a class "Test" under a namespace "TEST_NS".
In the main program, I've created a pointer to "Test" and would like to point to the "testfunc()" function. No problem...
I declare a private variable "foo" as a member of "Test", and the "testfunc()" function attempts to change the variable. This results in a segmentation fault.
Why does this happen?
I've created a simple example to show my issue. The segfault happens when I set foo = 1; in test.cpp
Here are the files:
main.cpp:
#include <iostream>
#include "test.h"
using namespace std;
int main () {
TEST_NS::Test * test;
test->testfunc();
return 0;
}
test.h:
#include <iostream>
namespace TEST_NS
{
class Test
{
int foo;
public:
Test();
~Test();
void testfunc();
};
}
test.cpp:
#include <iostream>
#include "test.h"
using namespace TEST_NS;
Test::Test() { }
Test::~Test() { }
void Test::testfunc()
{
std::cout << "This is testfunc()!" << std::endl;
foo = 1;
}
The code was compiled with
g++ main.cpp test.cpp -o test
And run with
./test
You need to instantiate an object of your class; try
TEST_NS::Test * test = new TEST_NS::Test();
test->testfunc();
Your main() function needs to change; the preferred way to write it is
int main () {
TEST_NS::Test test;
test.testfunc();
return 0;
}
If you really want to use a pointer (why?), then you should write:
int main () {
auto test = new TEST_NS::Test();
test->testfunc();
delete test;
return 0;
}
notice the addition of delete test;. But this is bad practice as it creates the potential for memory leaks, especially as more code is added (or if testfunc() throws an exception). If you really need to use pointers, it's much better to use std::unique_ptr<>.
int main () {
auto test = std::make_unique<TEST_NS::Test>();
test->testfunc();
return 0;
}
notice that this also gets rid of the explicit new which is generally a good idea, as well as the delete that had to be added; plus, it's exception-safe.
There is very little reason for "naked" new or delete in modern C++. Note that you can still get a "raw" pointer by using get(), although dereferencing would be preferred
void testfunc(TEST_NS::Test& test)
{
test.testfunc();
}
// ...
testfunc(*test);

How to invoke a C++ function after main() finishes

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.

void() issue - It doesn't print results

I am writing a program split in three different files:
1) An header named my.h;
A source cpp file named my.cpp;
The main file named use.cpp;
Here their statements:
/* Header file my.h
Define global variable foo and functions print and print_foo
to print results out */
extern int foo;
void print_foo();
void print(int);
/* Source file my.cpp where are defined the two funcionts print_foo() and print()
and in where it is called the library std_lib_facilities.h */
#include "stdafx.h"
#include "std_lib_facilities.h"
#include "my.h"
void print_foo() {
cout << "The value of foo is: " << foo << endl;
return;
}
void print(int i) {
cout << "The value of i is: " << i << endl;
return;
}
/ use.cpp : definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include "my.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int foo = 7;
int& i = foo;
i = 99;
char cc = '0';
while (cin >> cc) {
switch (cc) {
case '1':
void print_foo();
break;
case '2':
void print();
break;
default:
exit(EXIT_FAILURE);
}
}
return 0;
}
My main problem is that program compiles and run correctly but it doesn't print anything as I supposed.
How can I fix it?
Thank you!
Leo
To call a function specifying return type is not required. Correct
void print_foo(); // This actually declares a function prototype
to
print_foo();
and
print(i); // Pass i as argument
Drop the void from void print_foo(); and void print(); in the switch blocks.
Currently you're just declaring a function prototype; not actually calling the function.
Your extern int foo; approach, while syntactically valid, can make your codebase harder to scale and maintain: consider passing the parameter explicitly.
Your code claims to *"Define global variable foo..." as follows...
extern int foo;
...but that just declares that some translation unit will actually define it (without the leading extern qualifier). There's no actual variable in the code you've posted, which means your program shouldn't link unless some library you're using coincidentally has a foo symbol in it.
This shorter code condenses your problem:
#include <iostream>
extern int foo;
void f()
{
std::cout << foo << '\n';
}
int main() {
int foo = 7;
f();
}
You can see the compiler error message here, namely:
/tmp/ccZeGqgN.o: In function `f()':
main.cpp:(.text+0x6): undefined reference to `foo'
collect2: error: ld returned 1 exit status
You would put in the main function
case '1':
print_foo();
break;
Notice I erased the word "void" in the case 1. Because you don't redeclare the function there. You just use it.

"Warning: Can't find linker symbol for virtual table for value XXX value" using GCC and GDB (CodeBlocks)

I'm getting a runtime error ("memory can't be written") that, after inspection through the debugger, leads to the warning in the tittle.
The headers are the following:
componente.h:
#ifndef COMPONENTE_H
#define COMPONENTE_H
using namespace std;
class componente
{
int num_piezas;
int codigo;
char* proovedor;
public:
componente();
componente(int a, int b, const char* c);
virtual ~componente();
virtual void print();
};
#endif // COMPONENTE_H
complement.h implementation
#include "Componente.h"
#include <string.h>
#include <iostream>
componente::componente()
{
num_piezas = 0;
codigo = 0;
strcpy(proovedor, "");
//ctor
}
componente::componente(int a = 0, int b = 0, const char* c = "")
{
num_piezas = a;
codigo = b;
strcpy(proovedor, "");
}
componente::~componente()
{
delete proovedor;//dtor
}
void componente::print()
{
cout << "Proovedor: " << proovedor << endl;
cout << "Piezas: " << num_piezas << endl;
cout << "Codigo: " << codigo << endl;
}
teclado.h
#ifndef TECLADO_H
#define TECLADO_H
#include "Componente.h"
class teclado : public componente
{
int teclas;
public:
teclado();
teclado(int a, int b, int c, char* d);
virtual ~teclado();
void print();
};
#endif // TECLADO_H
teclado.h implementation
#include "teclado.h"
#include <iostream>
teclado::teclado() : componente()
{
teclas = 0;//ctor
}
teclado::~teclado()
{
teclas = 0;//dtor
}
teclado::teclado(int a = 0, int b = 0, int c = 0, char* d = "") : componente(a,b,d)
{
teclas = c;
}
void teclado::print()
{
cout << "Teclas: " << teclas << endl;
}
The main method where I get the runtime error is the following:
#include <iostream>
#include "teclado.h"
using namespace std;
int main()
{
componente a; // here I have the breakpoint where I check this warning
a.print();
return 0;
}
BUT, if instead of creating an "componente" object, I create a "teclado" object, I don't get the runtime error. I STILL get the warning during debugging, but the program behaves as expected:
#include <iostream>
#include "teclado.h"
using namespace std;
int main()
{
teclado a;
a.print();
return 0;
}
This returns "Teclas = 0" plus the "Press any key..." thing.
Do you have any idea why the linker is having troube with this? It doesn't show up when I invoke the virtual function, but before, during construction.
Two errors that I can see:
strcpy(proovedor, ""); // No memory has been allocated to `proovedor` and
// it is uninitialised.
As it is uninitialised this could be overwriting anywhere in the process memory, so could be corrupting the virtual table.
You could change this to (in both constructors):
proovedor = strdup("");
Destructor uses incorrect delete on proovedor:
delete proovedor; // should be delete[] proovedor
As this is C++ you should considering using std::string instead of char*.
If you do not change to std::string then you need to either:
Implement a copy constructor and assignment operator as the default versions are incorrect if you have a member variable that is dynamically allocated, or
Make the copy constructor and assignment operator private to make it impossible for them to be used.
Another source of this same message is that gdb can get confused by not-yet-initialized variables. (This answers the question title, but not the OP's question, since a web search led me here looking for an answer.)
Naturally, you shouldn't have uninitialized variables, but in my case gdb attempts to show function local variables even before they are declared/initialized.
Today I'm stepping through another developer's gtest case and this message was getting dumped to output every time the debugger stopped. In this case, the variable in question was declared on ~line 245, but the function started on ~line 202. Every time I stopped the debugger between these lines, I received the message.
I worked around the issue by moving the variable declaration to the top of the function.
For reference, I am testing with gdb version 7.11.1 in QtCreator 4.1.0 and I compiled with g++ version 5.4.1