Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A beginner's hello world C program?

Tags:

c

As I beginner, I typed the following hello world program on Code::Blocks -

#include<stdio.h>
main()
    {
        printf("Hello world \n");
    }

Now, I click on 'Build and Run', and the output screen shows 'Hello world'.

However, the book I am reading from, suggests me to remove certain elements of the program to see what errors occur in the program.

I made 2 changes. First, I removed \n from the program. (The book tells me that without \n, there will be an error running the program) However, when I click on 'Build and Run', the output screen gives me the same output it did when it was without any errors.

The second change I made was removing #include from the program. Even now, the output screen shows the same output it did when it was free from errors.

Why is this happening? Please tell me how to fix this?

The compiler I am using is GNU GCC compiler.

EDIT: As suggested, I added -wall, -wextra, -pedantic. Now, when I click on 'Build and Run', it says cannot find -1-wall, -1-wextra and -1-pedantic and the program doesn't run. How to fix this now?

like image 340
user52976 Avatar asked Jul 02 '15 18:07

user52976


1 Answers

Case 1: your book is wrong. Removing \n will never raise any error. \n means newline which will print a new line after Hello World.

Case 2: May be you are not building the code again, because without including the stdio (means standard input/output) you may not invoke printf() function if you use newer C standards (C99, C11). Read more about stdio.h.

Note that, in pre C99 standard if you remove the prototype (#include <stdio.h>) C will automatically provide an implicit declaration for a function. Which will look like this:

int printf();

means, it will take any number of arguments and return int. But in C99 implicit deceleration were removed. So most probably your compiler does not confront C99.

Take a look here, compile fine!

Read more about implicit declarations in c.

EDIT: As AnT mentioned in the comment, removing #include<stdio.h>, the call to printf will "compile" in pre-C99 version of language. However, the call will produce undefined behavior. Variadic functions (like printf) have to be declared with prototype before the call even in C89/90. Otherwise, the behavior is undefined.

like image 54
rakeb.mazharul Avatar answered Oct 12 '22 12:10

rakeb.mazharul