473,883 Members | 1,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why still use C?

no this is no trollposting and please don't get it wrong but iam very
curious why people still use C instead of other languages especially C++.

i heard people say C++ is slower than C but i can't believe that. in pieces
of the application where speed really matters you can still use "normal"
functions or even static methods which is basically the same.

in C there arent the simplest things present like constants, each struct and
enum have to be prefixed with "struct" and "enum". iam sure there is much
more.

i don't get it why people program in C and faking OOP features(functi on
pointers in structs..) instead of using C++. are they simply masochists or
is there a logical reason?

i feel C has to benefit against C++.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et
Nov 13 '05
687 23872
Derek Millar wrote:
Maybe this came up earlier in the thread and I missed it, but I don't
see why, if the main reason for casting malloc calls is C++ compatibility,
it doesn't make more sense to use a macro something like one of the ones
in this example:

#include <stdlib.h>

#ifdef __cplusplus
#define CXXCAST(x) static_cast<x>
#define CXXCAST2(x,y) static_cast<x>( y)
#else
#define CXXCAST(x)
#define CXXCAST2(x,y) y
#endif

int main(int argc, char* argv[]) {
char *c;

c = CXXCAST(char *) (malloc(10 * sizeof *c));
c = CXXCAST2(char *, malloc(10 * sizeof *c));

/* watch the leak */

return 0;
}
A C-style cast could be used if the static_cast isn't portable enough.
It seems like you get the best of both worlds here, unless you're
coding to a DS9000 or something where __cplusplus causes the C compiler
to explode. Am I overlooking something?


#ifdef __cplusplus
inline
char* char_malloc(siz e_t n) {
return static_cast<cha r*> malloc(n*sizeof (char)); }
#else //__cplusplus
inline static
char* char_malloc(siz e_t n) {
return (char*)malloc(n *sizeof(char)); }
#endif//__cplusplus

Nov 13 '05 #391
James Kuyper wrote:
Keith Thompson wrote:
...
The macros look fine, but the casts are still unnecessary and
potentially dangerous. Why not just

#define NEW(type) \
(malloc(sizeof( type)))

Because those dangerous casts are the key motivation for those macros.
This NEW() macro is intended to do something vaguely similar to the
'new' operator in C++: it allocates memory of the correct size and
returns a pointer to the correct type. The advantage is that the type
used in the cast is always correctly matched with the type used in the
sizeof(). The disadvantage is that there's no mandatory warning if
there's no declaration of malloc() in scope, or a declaration with the
wrong return type.


Your logic is flawed.
Better C compilers can and do issue a warning
if malloc is not declared in the scope where it is invoked.
The ANSI/ISO C standards do *not* specify all of the behavior
of a *good* C compiler -- the market place does.
If your C compiler fails to warn you about undeclared functions,
You should be shopping for a better C compiler
and you should *not* rely upon a message a confused compiler about
conversion from an integer to a pointer without a cast
to help you diagnose the actual problem.

Nov 13 '05 #392
"E. Robert Tisdale" wrote:

James Kuyper wrote:
Keith Thompson wrote:
...
The macros look fine, but the casts are still unnecessary and
potentially dangerous. Why not just

#define NEW(type) \
(malloc(sizeof( type)))

Because those dangerous casts are the key motivation for those macros.
This NEW() macro is intended to do something vaguely similar to the
'new' operator in C++: it allocates memory of the correct size and
returns a pointer to the correct type. The advantage is that the type
used in the cast is always correctly matched with the type used in the
sizeof(). The disadvantage is that there's no mandatory warning if ^^^^^^^^^ there's no declaration of malloc() in scope, or a declaration with the
wrong return type.


Your logic is flawed.


It not my logic; I'm just trying to help explains someone else's logic.
Personally, I think not casting it is better; however, I can see the
other side's arguments.
Better C compilers can and do issue a warning


It's not mandatory.

--
James Kuyper
MODIS Level 1 Lead
Science Data Support Team
(301) 352-2150
Nov 13 '05 #393
Fergus Henderson wrote:

<snip>
I tend to use macros such as the following, defined in a per-project
header file:

#include <stdlib.h>

#define NEW(type) \
((type *) malloc(sizeof(t ype)))
Consider #define NEW(size) malloc(size)

#define NEW_ARRAY(type, num) \
((type *) malloc((num) * sizeof(type)))
Consider #define NEW_ARRAY(size, nobjs) malloc(size * nobjs) - although
personally I'd prefer to #define NEW_ARRAY(size) malloc(size)
#define RESIZE_ARRAY(pt r, type, num) \
((type *) realloc((ptr), (num) * sizeof(type)))
Consider #define RESIZE_ARRAY(pt r, num) realloc(ptr, num * sizeof *ptr)
I consider the use of such macros to be good practice, not bad practice.
Depends on the macro. :-)
They are safer than using malloc() manually, since they avoid the
possibility that you accidentally specify a type inside the sizeof() which
doesn't match the type of the pointer which you are assigning the result
to.
But it is only by putting a type in the sizeof that you risk the accident!
With the following technique, there is no such risk.

T *p = malloc(N * sizeof *p);

Using a single set of macros throughout the application also provides
a good place to hook in if any special application-specific handling of
out-of-memory conditions is desired.


That's another issue, and of course in that regard you are quite right. (Not
just out-of-memory - even more useful for memory usage reporting and leak
checking.)

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #394
Derek Millar wrote:
Richard Heathfield <do******@addre ss.co.uk.invali d> writes:
Derek Millar wrote:

<snip>
> A C-style cast could be used if the static_cast isn't portable enough.
> It seems like you get the best of both worlds here, unless you're
> coding to a DS9000 or something where __cplusplus causes the C compiler
> to explode. Am I overlooking something?
From my perspective at least, yes, you're overlooking the fact that good
C++ code tends to look nothing like good C code; nowadays, I never (okay,
never

....

Well, sure, but as I understand it, the requirement in this particular
situation is to have a single piece of code which compiles under both
C and C++,


But it is this very "requiremen t" which I'm challenging. With the obvious
exception of Mr Plauger (who is shipping a standard library implementation
which must be able to work with both C and C++) and others of his ilk, I am
not convinced that the "requiremen t" is a valid one.
in which case it seems to make sense to take as much advantage
as possible of the safety features of each language (i.e., no cast for
malloc in C and static_cast in C++).
If you must do this damn silly thing, then that's a relatively non-silly way
to do it, yes.
Whether there's a general need for
that sort of code or not is a separate question.


I think it's all part of the same question, BICBW.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #395
"E. Robert Tisdale" wrote:
Your logic is flawed.
Better C compilers can and do issue a warning

Not one of your better trolls.

In point of fact, many compilers to not warn of that fact, which is why
we deal with the problem on comp.lang.c all the time.

Brian Rodenborn
Nov 13 '05 #396
James Kuyper wrote:
It's not mandatory.


But we *do* expect programmers to exercise *some* discretion
when choosing a C compiler.
C compiler developers don't care about the mandates
of the ANSI/ISO C standards.
They only care about pleasing their customers.
They conform to the standards only to the extent
that doing so pleases their customers.
Conforming to the ANSI/ISO standards is *not* sufficient
to guarantee that their compilers will be successful.

If your C compiler fails to detect and warn you
about undeclared functions, you have a deficient compiler.
You should be shopping for a better C compiler.

Nov 13 '05 #397
On 20 Oct 2003 08:53:53 -0700,
James Kuyper <ku****@wizard. net> wrote:

Back to the actual issues, here's another case:

int *y = (int*)malloc(10 00*sizeof(doubl e)); // would be unnoticed

The type checking that you get from

T *p = (T*)malloc(expr ession);

is not very useful, because it's extremely rare to change one of the
'T's without changing the other one, and when it does happen the
correction is usually that you need to change the second one to match
the first. That correction produces exactly the same effect that you
would get automatically if you removed the cast.

On the other hand, the cast disables the validity check that you would
otherwise get if the declaration of malloc() is either missing or
specifies an incompatible return type, and that's a much more
important validity check.

I don't cast malloc, and I tell all the junior programmers not to cast
malloc (because they regularly forget to #include <stdlib.h> and they
regularly use casts incorrectly to hide compiler warnings. I always
look closely at any cast in code I have to review. Fewer casts just
makes my job easier)

But one case where I can think a cast might help.
(legacy code follows :-)
/*
* (17 Jan 1986)
* globals are bad so I've put all 1756 of them into a single structure
* so now there is only one global.
*/

struct {
T* ptr;
....
} put_all_global_ vars_in_a_struc t_so_there_is_o nly_one_global;

<thousands of lines of code>

void setup(void)
{
<seven hundred lines of initialization>

put_all_global_ vars_in_a_struc t_so_there_is_o nly_one_global. ptr
= (T*)malloc(size of(T) * 354);

<several hundred more lines of initialization>

put_all_global_ vars_in_a_struc t_so_there_is_o nly_one_global. ptr
= (T*)malloc(size of(T) * 4755);

<several hundred more lines of initialization>
}
In all those lines of initialization there are ifs/elses etc liberally
scattered etc,etc, so the mallocs don't actually result in a memory
leak although it isn't obvious how on earth they don't.

You now decide you need to change the type of ptr. The casts at least
mean you get a warning if you miss one of the changes.

IME, it's a wonder most legacy code works at all, let alone as well
as it does. IIRC CMM estimates that a "level 1" organisation has about
20 bugs per kloc. A significant proportion of the legacy code I have
had to work with has at least that many faults immediately visible to
the Mk1 eyeball before attempting to analyse the code. Unfortunately
attempting to fix the obvious issues often results in a cascading
change so all changes have a minimum disturbance goal.

Tim.

--
God said, "div D = rho, div B = 0, curl E = - @B/@t, curl H = J + @D/@t,"
and there was light.

http://tjw.hn.org/ http://www.locofungus.btinternet.co.uk/
Nov 13 '05 #398
James Kuyper <ku****@saicmod is.com> writes:
Keith Thompson wrote:
...
The macros look fine, but the casts are still unnecessary and
potentially dangerous. Why not just

#define NEW(type) \
(malloc(sizeof( type)))


Because those dangerous casts are the key motivation for those macros.
This NEW() macro is intended to do something vaguely similar to the
'new' operator in C++: it allocates memory of the correct size and
returns a pointer to the correct type. The advantage is that the type
used in the cast is always correctly matched with the type used in the
sizeof(). The disadvantage is that there's no mandatory warning if
there's no declaration of malloc() in scope, or a declaration with the
wrong return type.


I was just about to post a followup saying that there is absolutely no
advantage in casting the result of malloc. Then, to my surprise, I
thought of one.

Given the original definition of NEW:

#define NEW(type) ((type *)malloc(sizeof (type)))

the following is legal:

int *ip = NEW(int);

but the following produces an error message:

float *fp = NEW(int);

Without the cast, the error is not diagnosed.

I still wouldn't use a cast if the call to malloc is explicit, rather
than hidden within a macro; in that context, the cast is more likely
to mask an error than to expose one.

The real problem is that a cast is too blunt an instrument. If there
were an operator that meant "convert a void* value to FOO*", and that
would cause a diagnostic if applied to something of a type other than
void*, it would be perfectly sensible to apply such an operator to a
malloc() call. Unfortunately, all we have is the cast operator, which
says "convert this value to FOO*; I don't particularly care what its
original type is", so it's (usually) safer to depend on the implicit
conversion from void* to any object pointer type.

--
Keith Thompson (The_Other_Keit h) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #399
On Thu, 23 Oct 2003 22:16:32 GMT, in comp.lang.c , Keith Thompson
<ks*@cts.com> wrote:
I was just about to post a followup saying that there is absolutely no
advantage in casting the result of malloc. Then, to my surprise, I
thought of one.

Given the original definition of NEW:

#define NEW(type) ((type *)malloc(sizeof (type)))


ISTR that we covered this elsethread by defining the macro better, at
the expense of looking less like C++. Good.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #400

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
11266
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL) on the server because of that. Our site will have an SSL certificate next week, so I would like to use AIM instead of SIM, however, I don't know how to send data via POST over https and recieve data from the Authorize.net server over an https...
2
5865
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues to execute the code until the browser send his reply to the header instruction. So an exit(); after each redirection won't hurt at all
3
23053
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which field is completed.
0
8508
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. 354 roberto@ausone:Build/php-4.3.2> ldd /opt/php4/bin/php libsablot.so.0 => /usr/local/lib/libsablot.so.0 libstdc++.so.5 => /usr/local/lib/libstdc++.so.5 libm.so.1 => /usr/lib/libm.so.1
1
8621
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the column below. The viewer can select states from the drop down lists above the other two columns as well. If the viewer selects only one, only one column fills. If the viewer selects two states, two columns fill. Etc. I could, if appropriate, have...
4
18317
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the user comes back to a page where he had a submitted POST data the browser keeps telling that the data has expired and asks if repost. How to avoid that? I tried registering all POST and GET vars as SESSION vars but
1
6890
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url http://www.mis.gla.ac.uk/biquery/training/ but each of the courses held have maximum of 8 people that could be
2
31461
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value to :parameter I dont like the idea of making the SQL statement on the fly without binding parameters as I dont want a highly polluted SQL cache.
3
23617
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the results of the picture half the size. The PHP I have installed support 1.62 or higher. And all I would like to do is take and image and make it fit a 3x3. Any suggestions to where I should read or look would be appreciated.
0
9935
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9791
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10844
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10410
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9571
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7970
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5797
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5990
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3231
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.