Is C strongly typed?
Asked Answered
J

18

100

To quote Wikipedia:

Two commonly used languages that support many kinds of implicit conversion are C and C++, and it is sometimes claimed that these are weakly typed languages. However, others argue that these languages place enough restrictions on how operands of different types can be mixed, that the two should be regarded as strongly typed languages.

Is there a more definitive answer?

Janenejanenna answered 9/1, 2009 at 23:54 Comment(8)
To a C programmer strong typing means pressing the keys harder.Benford
C is on the weak side in the typing continuum. But there are enough items on either side that you can argue either way. While you're at it you might as well ask (vi or emacs, netbeans or eclipse, etc.)Pretor
The state of play on Wikipedia was bad enough that I felt compelled to edit several Wikipedia pages. Maybe things are a little better now. Maybe.Robi
Re: Dan's comment (to give credit where it's due) Peter van der Linden's book "Expert C Programming" contains the following line: "To this day, many C programmers believe that 'strong typing just means pounding extra hard on the keyboard."Leptophyllous
Very good question !!!Katusha
Well, since the creator of C++, Bjarne Stroustrup says in The C++ Programming Language (4th edition) that: C++ programming is based on strong static type checking, and most techniques aim at achieving a high level of abstraction and a direct representation of the programmer’s ideas., I feel that C++ should be taken out of the Wikipedia sentence.Orthicon
The page no longer says that, and it was never true. I know of no one who claims that C should be regarded as strongly typed language ... it certainly isn't one, regardless of what the term even means.Grayish
I would say both C and C++ are strongly typed languages with loopholes in their type systems.Stichometry
R
178

"Strongly typed" and "weakly typed" are terms that have no widely agreed-upon technical meaning. Terms that do have a well-defined meaning are

  • Dynamically typed means that types are attached to values at run time, and an attempt to mix values of different types may cause a "run-time type error". For example, if in Scheme you attempt to add one to true by writing (+ 1 #t) this will cause an error. You encounter the error only if you attempt to execute the offending code.

  • Statically typed means that types are checked at compile time, and a program that does not have a static type is rejected by the compiler. For example, if in ML you attempt to add one to true by writing 1 + true, the program will be rejected with a (probably cryptic) error message. You always get the error even if the code might never be executed.

Different people prefer different systems according in part to how much they value flexibility and how much they worry about run-time errors.

Sometimes "strongly typed" is used loosely to mean "statically typed", and "weakly typed" is used incorrectly to mean "dynamically typed". A better use for the term "strongly typed" is that "you cannot work around or subvert the type system", whereas "weakly typed" means "there are loopholes in the type system". Perversely, most languages with static type systems have loopholes, while many languages with dynamic type systems have no loopholes.

None of these terms are connected in any way with the number of implicit conversions available in a language.

If you want to talk precisely about programming languages, it is best to avoid the terms "strongly typed" and "weakly typed". I would say that C is a language that is statically typed but that has a lot of loopholes. One loophole is that you can freely cast any pointer type to any other pointer type. You can also create a loophole between any two types of your choice by declaring a C union that has two members, one for each of the types in question.

I have written more about static and dynamic typing at why-interpreted-langs-are-mostly-ducktyped-while-compiled-have-strong-typing.

Robi answered 10/1, 2009 at 2:24 Comment(10)
Where did you get the definitions you suggest for strong/weak typing (the loophole thing)?Janenejanenna
Why would you need a "loophole" in a dynamic typing environment?Wyrick
@Sydius: From spending much of the last 20 years hanging out with people who design, build, and analyze programming languages and type systems. That's my paid job :-)Robi
@Chris: I've never seen a dynamically typed language with 'loophole'. The common use of loophole is to work with a run-time system or OS, e.g., take a raw address and convert it to a pointer to a well-behaved language value. You could do this in a dynamic setting but I don't know of any attempts.Robi
@NormanRamsey I think that Chris was referring with his question to: whereas "weakly typed" means "there are loopholes in the type systemPasskey
@NormanRamsey Suggest replacing "types are attached to values at run time" with "the types of all expressions may not be known until run time." Values always have types whether a language is statically or dynamically typed. The distinction is manifested only when we have expressions with variables. It's easy to confuse the term "values" and "variables" in informal conversations, but here in this answer it's better to be precise.Inness
The answer is wrong in the sense that "subverting the type system" is related to "type unsafety" and not to weak typing, however loosely these both are defined.Esch
@JFA but adding an int to a string makes perfect sense in C and not in python, given that in C you are adding to a pointerOdonnell
Elegantly explained! I always believed that the creators of C and C++ always wanted those to be strongly typed(yes really!) languages but the loopholes in their design prevented them from being so. And, now with languages like Rust, both C and C++ feel like a generation behind.Stichometry
I thought "strong typing" (usually) meant "the language will exit/fail/throw at run-time upon being asked to perform an operation using the wrong type" whereas "weak typing" meant "the language will simply perform the same operations using the wrong type at run-time as if it were the right one, without checking the value's form/type first". So C would be static & weak, whereas e.g. JS would be dynamic & strong.Torrens
F
24

It's hard to classify every language into 'weakly' or 'strongly' typed -- it's more of a continuum. But, in comparison to other languages, C is fairly strongly typed. Every object has a compile-time type, and the compiler will let you know (loudly) if you're doing something with an object that its type doesn't let you do. For example, you can't call functions with the wrong types of parameters, access struct/union members which don't exist, etc.

But there are a few weaknesses. One major weakness is typecasts - they essentially say that you're going to be mucking around with the types of objects, and the compiler should be quiet (when it can). void* is also another weakness -- it's a generic pointer to an unknown type, and when you use them, you have to be extra careful that you're doing the right thing. The compiler can't statically check most uses of void*. void* can also be converted to a pointer to any type without a cast (only in C, not in C++), which is another weakness.

Fitzwater answered 10/1, 2009 at 0:1 Comment(3)
Nice answer, although "typecasts...and compiler should be quiet" bothers me. A typecast is not like shutting off a warning, it actually changes the interpretation of the value being referenced.Viewfinder
You're confusing "static" and "strong" in relation to typing. These two concepts are independent of each other.Bosnia
Dennis Richie (C author) called C 'strongly typed and weakly checked'Russon
F
15

C is considered to be weakly typed, because you can convert any type to any other type through a cast, without a compiler error. You can read more about the issue here.

Firedrake answered 10/1, 2009 at 0:26 Comment(3)
wikipedia is misleading here. C is strongly typed, types are very valid and the compiler will barf if you get them wrong, however, C also provides features for you to bypass this. Compare to languages like BCPL that only have a 'byte' type.Eyeglass
Weakly typed doesn't mean a language doesn't have any types, it just means that types can be implicitly coerced from one type to another. Compare to Python, a strongly typed language in which you must explicitly convert types with function calls.Firedrake
does able to cast a thing in C also contribute to it being a weak type.?? I have this doubt for like foreverCanorous
I
11

The literature isn't clear about this. I think that strongly typed isn't yes/no, there are varying degrees of strong typing.

A programming language has a specification of how it executes programs. Sometimes it's not clear how to execute with certain programs. For example, programs that try to subtract a string from a number. Or programs that divide by zero. There are several ways to deal with these conditions. Some languages have rules for dealing with these errors (for example they throw an exception). Other languages just don't have rules to deal with these situations. Those languages generally have type systems to prevent compiling programs that lead to unspecified behavior. And there also exist languages that have unspecified behavior and don't have a type system to prevent these errors at compile time (if you write a program that hits unspecified behavior it might launch the missiles).

So:

Languages that specify what happens at runtime in every case (like adding a number to a string) are called dynamically typed. Languages that prevent executing programs with errors at compile time are statically typed. Languages that don't specify what happens and also don't have a type system to prevent errors are called weakly typed.

So is Java statically typed? Yes, because its type system disallows subtracting a string from a number. No, because it allows you to divide by zero. You could prevent division by zero at compile time with a type system. For example by creating a number type that can't be zero (e.g. NonZeroInt), and only allow to divide by numbers that have this type.

So is C strongly typed or weakly typed? C is strongly typed because the type system disallows some type errors. But it's weakly typed in other cases when it's undefined what happens (and the type system doesn't protect you).

Idiomorphic answered 10/1, 2009 at 0:16 Comment(2)
I like your aligning of dynamic and static as forms of strong, vs weak. However, I'm not sure I get your point about statically typed systems stopping divide by zero. If my statically typed int gets a value from the user or command line arguments or a file, there's nothing the compiler can do to stop that being a zero!Kaduna
There are static type systems that prevent this, but most languages are either weakly or dynamically "typed" with respect to division by zero, because it's undefined behaviour (C) or they throw an exception (Java).Idiomorphic
S
7

C is more strongly typed than Javascript and less strongly typed than Ada.

I'd say it falls more into the strongly typed side of the continuum. but someone else might disagree (even if they're wrong).

How's that for definitive?

Second answered 9/1, 2009 at 23:59 Comment(3)
It was a somewhat tongue-in-cheek answer. But do elaborate on the wrongness.Second
Javascript is strongly typed. It just isn't statically typed. All type checks occur at runtime (dynamic, not static) but they do occur and the do prevent you from corrupting memory (one aspect of strong typing).Bosnia
Well, as Norm Ramsey's very good answer indicates, "strongly typed" and "weakly typed" are not particularly well defined terms. Also, as far as Javascript being strongly typed, some might believe that ("4" / "2") being a valid Javascript expression might indicate otherwise.Second
M
7

According to Dennis Ritchie (creator of C ) and Brian Kernighan , C is not a strongly typed language. Following lines are from the book The C programming language page 3 paragraph 5

C is not a strongly-typed language, but as it has evolved, its type checking has been strengthened.

Mopboard answered 8/9, 2017 at 13:58 Comment(0)
P
5

C is considered statically typed (you can't have a variable change from int to float). Once a variable is declared it is stuck that way.

But it is considered weakly typed because the types can be flip flopped.

What is 0? '\0', FALSE, 0.0, etc..

in many languages you can't say IF (variable) because conditions will only take boolean values from boolean expressions. These are more strongly typed. The same applies to going between characters and integers.

basically c has two main simple data types, integers and floating point numbers (though various precisions). Everything else booleans, enums (not simple but it fits), etc. are implemented as one of those. Even characters are basically integers.

Compare to other languages where there are string types, enum types that can only be assigned to the defined values, boolean types where only expressions that generate booleans or true/false can be used.

But you can argue that compared to Perl C is strongly typed. So it is one of those famous arguments (vi vs emacs, linux vs windows, etc.). C# is stronger typed than C. Basically you can argue either way. And your answers will probably go both ways :) Also some textbooks/web pages will say C is weakly typed, and some will say C is strongly typed. If you go to wikipedia the C entry says "partially weak typing". I would say compared to Python C is weakly typed. So Python/C#, C, Perl on the continuum.

Pretor answered 10/1, 2009 at 0:33 Comment(4)
Please explain your reasoning that Perl is less strongly typed than C.Setsukosett
print "Testing" + 0 # perl will do 0; $var = "string"; $var = 1; $var = 123.4; What kind of variable is it?Pretor
In C char *test = "testing"; printf (testing + 0); will still be a string, it's just that in C the index will change if instead of zero I use a number. It is still pretty weak, but a bit stronger then perl. char * test; test=0; test = 123.4; test = "c";...my compiler generates errorsPretor
the error says that a cast is required. Still it is a bit stronger of a type check than Perl so on the continuum I have to say C is more strongly typed than Perl. You can still go test = (char *) and then use 0, 123.4, 'C', etc.. But it is an error to just do it.Pretor
C
5

Plenty of good answers here. I want to bring up an important point from Real World Haskell:

It is useful to be aware that many language communities have their own definitions of a “strong type”. Nevertheless, we will speak briefly and in broad terms about the notion of strength in type systems.

(snip)

The fireworks around type systems have their roots in ordinary English, where people attach notions of value to the words “weak” and “strong”: we usually think of strength as better than weakness. Many more programmers speak plain English than academic jargon, and quite often academics really are throwing brickbats at whatever type system doesn't suit their fancy. The result is often that popular Internet pastime, a flame war.

So, look at the answers about C and C++, but remember that 'strong' and 'weak' do not map to 'good' and 'bad'.

Collocate answered 10/1, 2009 at 20:50 Comment(0)
L
3

In my opinion, C/C++ are strongly typed. The type of hacks that allow types to be converted (void*) are there because of C's closeness to the machine. In other words, you can call assembler commands from Pascal and manipulate pointers and Pascal is still regarded as a strongly typed language. You can call assembler and C executables from Java through JNI but it doesn't make Java weakly typed.

C just has assembler "embedded" in it with raw pointers and such.

Leven answered 9/1, 2009 at 23:58 Comment(0)
G
2

The term strongly typed doesn't have a agreed-upon definition. Therefore, unless you define what you mean by "strongly typed", it is impossible to answer your question.

In my experience, the terms "strongly typed" and "weakly typed" are used exclusively by trolls, because their lack of definitions allows the trolls to redefine them mid-argument to suit their agenda. Other than for starting flamewars, these terms are pretty much useless.

You might also want to take a look at What are the key aspects of a strongly typed language? here on StackOverflow.

Granlund answered 10/1, 2009 at 11:38 Comment(3)
I disagree. "Strongly typed" means that it is possible to determine the data type of a value, and only operations appropriate for that type are allowed. "Dynamically" and "statically" address when that determination can be made.Intort
You do realize the irony of trying to disprove the assertion that there is no agreed-upon definition by introducing yet another definition, right?Sullins
@Jorg: Not trying to introduce another one; just stating the one commonly used in the circles in which I move.Intort
U
1

There is a continuum with multiple parallel avenues between "weakly typed" and "strongly typed", two terms which are not even well defined.

C is statically typed, in that the compiler knows what the declared type of every local variable and struct member is.

Dynamically typed languages might still be strongly typed, if each object has a specific type but there is no way for the compiler to know that type.

Urumchi answered 10/1, 2009 at 0:53 Comment(0)
S
1

I would say that C is as strongly typed as your compiler / platform dictates. For instance, if you are building on a strict platform, dereferencing a type punned pointer is likely going to break:

void m_free(void **p)
{
        if (*p != NULL) {
                free(*p);
                *p = NULL;
        }
}

....
char *str = strdup("foo");
m_free((void **) &foo);

Now, if you told the compiler to skip strict aliasing, it would be a non issue, but not very portable. So, in that sense, pushing the bounds of the language is possible but probably not the best idea. That goes a step beyond typical casting, i.e. casting int as long and really shows one of the possible pitfalls of void.

So, I would say C is basically strictly typed, but its various compilers presume that the programmer knows best and allows some flexibility. This really depends on the compiler, some would not pick up on that potential oops. So in that sense, the compiler of choice really plays a role when answering the question. What is correct often differs from what your compiler will allow you to get away with.

Sarisarid answered 10/1, 2009 at 2:1 Comment(0)
I
1

Not strongly typed.

Consider what the following function prototype tells you about the data types of the arguments:

void func (int n, char ch, ...);

Nothing. So I suggest that strong typing does not apply here.

Intort answered 10/1, 2009 at 3:7 Comment(3)
Huh? It tell's you there's an int, followed by a char, followed by any number of arguments of any type. That's not "nothing".Armallas
The ... tells you nothing about the types of the arguments that are passed. It's true that the type of the function itself is know. That's what Software Monkey said.Legionnaire
Those "any number of arguments of any type" are what I'm talking about. A chain is only as strong as its weakest link.Intort
D
1

The “classic” definition of strongly typed is that the language forces the programmer to be explicit in telling the compiler the tupe of each variable so that it can ensure the behavior you get is what you expected. Its purpose is to detect and report an entire class of problems prior to attempting to run the code.

The problem with runtime detection of such problems is that most code contains infrequently run lines, particularly those designed for error checking. These may be run so rarely that some type problems are never seen by the original programmer and as a result escape into production. This can be avoided by writing a thorough test bench that exercises every line of code in every function, but I’ve rarely seen that done.

Some people are using the C Programming Language book as a reference as to whether the author thought C was strongly typed. This is misleading. When the book was written Cs type checking was not the same as it was when the C standard was adopted. C type checking became more strict over time and the behavior of implicit type conversions is now thoroughly spelled out in the standard.

Casts and void pointers are provided in C as an explicit way to bypass the type checking. Using them as proof C is loosely typed is disingenuous. It dismisses the entire part of the language that exists solely to define types and enforce consistency on the grounds there’s a workaround. It’s like saying seatbelts are worthless because some people don’t use them. Even with casts and void pointers, tupe definitions are still required, types are still checked, and type errors caught for the vast majority of lines of codes I think it’s fairer to say C is a strongly typed language with mechanisms to allow the knowledgeable user to bypass type checking should they feel they need to do so.

Dada answered 20/4 at 22:18 Comment(0)
D
0

What is the reason for your query? The reason I ask is this is sort of a minor difference and your particular usage of "strongly-typed" might need more or less clarification. I would definitely say that Java and other languages have tighter restrictions on implicit type conversation.

Delegation answered 10/1, 2009 at 0:1 Comment(2)
Mostly curiosity, but I am applying for a C position, and wanted to know in case they quiz me about it.Janenejanenna
Then probably the longer answer which gives the nuances of what "strongly typed" is the best approach rather than just saying "yes" or "no."Delegation
D
0

It is difficult to provide a concrete answer when there isn't a concrete definition of "strongly typed". I would say that C is strongly typed in that every variable and every expression has a type but weakly typed in that it allows you to change types using casts and to reinterpret the representation of one type as another.

Dana answered 10/1, 2009 at 0:44 Comment(1)
There is an official def. for strongly typed. It says that a sys. is S.T. when one guarantees that there is no running time type error. Example: ML, Haskell. This is useful to make the system omit type tags inside objects, and however apply the operators on correct types. Because we know before execution that there is no need of tags in objects. Because C has cast and pointer access to arbitrary memo, C is not s.t.Acculturate
C
0

c is weakly typed, b is typeless.

Cis answered 6/9, 2010 at 9:16 Comment(1)
This answer is excessively short given the question.Familiarity
K
-3

I'd say it is strongly types as every expression has a type that is not a function of it's value; e.i. it can be known before runtime.

OTOH I'm not sure that is the correct description of strongly typed. The only stronger claim I can see reason for a language to make would be the assurance that you can't subvert the type system at runtime via reinterpret type casts, unions, calling into other languages, pointers, assembly language, etc. Languages like this exist but are so crippled that they seem to not be of much interest to programmers outside of high assurance and academia. As pointed out by someone, to really do that right you start needing to have types like nonZeroInt and whatnot. Yuck.

Kriss answered 10/1, 2009 at 0:21 Comment(1)
What isn't? My definition of strongly typed or C?Kriss

© 2022 - 2024 — McMap. All rights reserved.