For starters in C operators == and != are named equality operators. The result of the equality operator ==
is integer value 1
if two operands of an expression with the equality operator are equal each other and 0
otherwise. So you could just write
int i = 7;
int j = 7;
int k = i == j;
or
int k;
int i = 7;
int j = 7;
k = i == j;
But if processing is more complex and compound statements include more statements apart from a simple assignment you indeed need to use if-else statements.
Pay attention to that variables have scopes. Variables declared in blocks have block scopes. Variables in inner scopes hide variables with the same name declared in enclosing scopes.
So relative to your program the variable k
declared in if and else parts of the if statement
if( i==j)
{
int k = 1;
}
else
{
int k = 0;
}
hides the variable k
declared before the if statement
int main()
{
int k;
//...
And the variables k
declared in the if and else parts of the if statement are not visible and alive after the if statement.
Thus in this call of printf
printf("%d" , k);
there is an attempt to output the variable k
declared before the if statement. As the variable has automatic storage duration then it is not initialized implicitly. As a result the call of printf
invokes undefined behavior.
To refer to the variable k
declared in the beginning of main in the if statement you need just to write within the if statement
if( i==j)
{
k = 1;
}
else
{
k = 0;
}
That is instead of declaring new variables in inner scopes with the same name k
you need just to refer the original variable k
declared before the if statement using the assignment (expression) statement.
Nevertheless you may declare a variable with the same name in an inner scope as a variable declared in an outer scope provided that you will use storage class specifier extern
that refers to a file scope variable.
Here is a demonstration program
#include <stdio.h>
int k;
int main(void)
{
int i = 7;
int j = 7;
if( i==j)
{
extern int k;
k = 1;
}
else
{
extern int k;
k = 0;
}
printf("k == %d\n" , k);
}
The declaration of the variable k
before main is called tentative definition. Declarations in the if statement
if( i==j)
{
extern int k;
k = 1;
}
else
{
extern int k;
k = 0;
}
refer to the variable k
declared in the file scope. So assignment statements within the if statement change that variable.
k
s do you have and which one do you print?k
inside brackets takes precedence over anyk
variable already declared in outer scopes. Here's where a good C book will be handy.int k = 1
but just usek = 1