C integers, possible overflow

I am trying to make a C program that will count and print the number of tabs, spaces, and lines entered by the user. The problem is, when he prints those numbers, they go crazy. Here is my program code:

int c, b, t, nl;
b, t, nl = 0, 0, 0;
while ((c = getchar()) != EOF) 
{
    if (c == '\b') 
        b++;
    if (c == '\t') 
        t++;
    if (c == '\n') 
        nl++;
}
printf("b=%d t=%d nl=%d\n", b, t, nl);

      

When I enter some data from terminal (3 lines, one space, one tab), the result is: b = 1899313536, t = 32768 and nl = 3.

+3


source to share


4 answers


The problem with this line:

b, t, nl = 0, 0, 0;

      

It uses a comma operator on both sides of the destination, so it is only nl

initialized to zero. There are no side effects to evaluate b

, t

on the left side * and two trailing zeros on the right side of the operator =

(note that assignment takes precedence over comma operator).

Change it to:



b = t = nl = 0;

      

which effectively means (since the operator =

has right associativity):

b = (t = (nl = 0));

      

* if b

or t

not declared as volatile

(since reading such an object is considered a side effect by the C standard)

+12


source


b

is uinintiaized, this expression is incorrect

b, t, nl = 0, 0, 0;

      



it initializes only nl

, it should be

b = t = nl = 0;

      

+3


source


Unlike Lua or several other languages ​​that allow you to assign multiple variables in a single expression

v1, v2, v3 = c1, c2, c3; // <<== This is not a valid C syntax.

      

C requires you to assign them separately:

b = 0;
t = 0;
nl = 0;

      

Better yet, you could initialize variables during declaration, like this:

int c, b=0, t=0, nl=0;

      

The reason your current code is compiling is a little curious: it treats commas in your code as comma operators, which are legal on both sides of the destination.

+2


source


These are garbage values. You need to assign variables b

, t

and nl

equal to 0.

+2


source







All Articles