Warnings for C programming
"Undetectable null bugs" from dead bytes:
The following code shows an example of a variable declared but not set to a value. Instead of returning the familiar "null", it returns what was left in the memory used for storing the variable, in this case, number 64:
// This is isolated code
int ghost;
printf("%d",ghost);
// This is console io
in > Run code
out > 64
Turning negative mistakenly
printf()
accesses data through the variable name, receives bytes, and converts them into specific formats, hence print"f
". Sometimes there is a mismatch between the type of variable put into the printf()
parenthesis and the %
tag used in the string constant. In the following case:
Variable Type | Mismatch Tag | Correct Tag |
---|---|---|
unsigned integer | %d etc. |
%u |
double | %d etc. |
%f |
// This is isolated code
unsigned int spook = 0xffffffff;
//4 Bytes are filled
printf("%d",spook);
printf("\n");
printf("%u",spook);
// This is console io
in > Run code
out > -1
out > 4294967295
Any int
divided by int
results in int
, oddly enough
The arithmatic operation of division for integers is defined as follows:
let p and q be two signed integers, at least one is negative
p%q =def= sign(p)*(abs(p)%abs(q))
let a and b ve two unsigned integers,
define a%b such that:
0 <= a%b < b
b*n <= a < b*(n+1)
b*n + a%b = a
define p/q such that:
q*(p/q)+p%q = p
This means things get tricky when there's a remainder, when p
or q
is negative or when both misfortunes are faced:
//Code
int p = 5;
int q = -2;
printf("%d",p/q);
printf("%d",p%q);
//Console
in > Run Code
out > -2
out > 1
#define
means Replacing with unexpected Danger
If a constant is defined in the #define
part, don't set up variables of the same name. #define
means thorough replacement!
// HEAD
#define PIG 233f
//Main, isolated code
float pig = 2024f
//console
in > Run code
ERROR:
main.c:x:xx: note: in expansion of macro 'PIG'
| float P = 0.001f;
| ^
标签:code,Run,Warnings,int,programming,printf,define,out
From: https://www.cnblogs.com/great-cat-42/p/18289068