This second tutorial is about the use of the
printf() function in .c
When we use the printf() function, we have to add
the stdio.h include at the beginning
of the file:
#include <stdio.h>
int main()
{
printf("hello\n");
return 0;
}
Here we just print a simple text, "hello\n",
the char "\n" at the end, is there to add a
new-line.
gcc test1.c -o test1.exe ./test1.exe hello
the line return 0 at the end is there to
return an eventual error-code. with 0, it
means there was no error. the standard error-code in
case there was an error in the program is 1
you can check this return'd code with:
./test1.exe echo $? 0
in the previous tutorial, we saw some of the basic type's in .c
here is how to print an int:
#include <stdio.h>
int main()
{
int d;
d = 3;
printf("my-int, d: %d\n", d);
return 0;
}
test'ing:
$ gcc test2.c -o test2.exe $ ./test2.exe my-int, d: 3
A string example:
#include <stdio.h>
int main()
{
char s[] = "alpha";
printf("hello %s\n", s);
return 0;
}
testing:
$ gcc test3.c -o test3.exe $ ./test3.exe hello alpha
#include <stdio.h>
int main()
{
float f = 3.2;
printf("my-float: %f\n", f);
return 0;
}
$ gcc test4.c -o test4.exe $ ./test4.exe my-float: 3.200000
the standard format for a float is '%f',
but as you can see it will print a number of 0
zero's at the end, so we can use '%g'
in-stead:
#include <stdio.h>
int main()
{
float f = 3.2;
printf("my-float: %g\n", f);
return 0;
}
$ gcc test4b.c -o test4b.exe $ ./test4b.exe my-float: 3.2
here we write a print_stc() function
#include <stdio.h>
struct _stc {
int d1;
float f2;
char *s;
};
void
print_stc(struct _stc *stc)
{
printf("my-stc: {\n");
printf(" %d\n", stc->d1);
printf(" %g\n", stc->f2);
printf(" %s\n", stc->s);
printf("}\n");
}
int
main()
{
struct _stc stc = {
11,
3.4,
"hello"
};
print_stc(&stc);
return 0;
}
we provide the address of our struct with &,
so the function print_stc() recieves a pointer to
the structure, this is why in the prototype of our function
there is a '*' char before the name of the var.
as the function recieves a pointer, the field's are access'd
with ->.
$ gcc test5.c -o test5.exe
$ ./test5.exe
my-stc: {
11
3.4
hello
}
TODO
2026-01-15.a
© 2025 Florent Monnier
You can use this document according to the terms of either one of these licenses:
You can reuse the pieces of code according to the terms of either one of these licenses: