C language to determine whether the value of int long and other variables

  • 2020-04-02 01:08:38
  • OfStack

Of course, if you don't assign a value to a local variable, this will cause the whole program to crash, because its contents are pointed to the garbage memory by the system.
Here's a piece of code:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int globle_value;
int my_sum(int value1, int value2);
long my_sub(long value1, long value2);
int main(void)
{
 int auto_value_int;
 long auto_value_long;
 auto_value_int = my_sum(15, 9);
 auto_value_long = my_sub(12587, 22587);
 printf("globle_value : %dn", globle_value);
 printf("auto_value_int : %dn", auto_value_int);
 printf("auto_value_long : %ldn", auto_value_long);
 system("PAUSE");
 return 0;
}
int my_sum(int value1, int value2)
{
 return value1 + value2;
}
long my_sub(long value1, long value2)
{
 return value2 - value1;
}

Description:
I first defined a global variable, which, of course, was automatically initialized to 0 by the system, but two different types of local variables were not initialized, but were assigned by two function calls. Now, though, think about the question, did the two function calls execute successfully? If it doesn't work, or I don't get what I want, how do I know?

At first, the blogger also did not think of a good solution, also look up how others do, there is not much harvest, however, the blogger came up with a function in C language --sprintf, it can put different types of variables into the character array, we can determine later, whether the character array is empty.
Here is the modified code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int globle_value;
int my_sum(int value1, int value2);
long my_sub(long value1, long value2);
int main(void)
{
 int auto_value_int;
 long auto_value_long;
 char temp[20] = {0};
 auto_value_int = my_sum(15, 9);
 auto_value_long = my_sub(12587, 22587);
 printf("globle_value : %dn", globle_value);
 sprintf(temp, "%d", auto_value_int);
 if (strcmp(temp, "") != 0)
 {
  printf("auto_value_int : %dn", auto_value_int);
 }

 sprintf(temp, "%ld", auto_value_long);
 if (strcmp(temp, "") != 0)
 {
  printf("auto_value_long : %ldn", auto_value_long);
 }

 system("PAUSE");
 return 0;
}
int my_sum(int value1, int value2)
{
 return value1 + value2;
}
long my_sub(long value1, long value2)
{
 return value2 - value1;
}

The running screenshot is as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201307/201307111004054.jpg ">

Thus, the problem was solved.


Related articles: